change the value of every object in an array if 0 to null

Viewed 381

I have this for example:

const sample = [
  { id: 1, val1: 0, val4: 10 },
  { id: 10, val1: 1, val4: 10, val19: 0, val29: 0 },
  { id: 11, val1: 0, val4: 0, val19: 0, val29: 10 },
];

and I want to change every 0 value into null

const sample = [
  { id: 1, val1: null, val4: 10 },
  { id: 10, val1: 1, val4: 10, val19: null, val29: null },
  { id: 11, val1: null, any: null, sample: null, val29: 10 },
];

I know I need to use map but I'm having difficulty in accessing every object.

8 Answers

If you have no methods this might work too.

You stringify it and use an replacer function to replace all zeros to null. Then just parse it back.

Works for deeper nested objects aswell

const sample = [
  { id: 1, val1: 0, val4: 10 },
  { id: 10, val1: 1, val4: 10, val19: 0, val29: 0 },
  { id: 11, val1: 0, val4: 0, val19: 0, val29: 10 },
];

let str = JSON.stringify(sample,(k, v) =>  v === 0 ? null : v);
let result = JSON.parse(str);

console.log(result);

You need forEach if you do not want a new array

const sample = [ { id: 1, val1: 0, val4: 10 }, { id: 10, val1: 1, val4: 10, val19: 0, val29: 0 }, { id: 11, val1: 0, val4: 0, val19: 0, val29: 10 }];

sample.forEach(item => { 
  for (val in item) item[val] = item[val] === 0 ? null : item[val] 
});
console.log(sample)

You may want to do loop through the list and then for every property in the object you check for val

const sample = [
  { id: 1, val1: 0, val4: 10 },
  { id: 10, val1: 1, val4: 10, val19: 0, val29: 0 },
  { id: 11, val1: 0, val4: 0, val19: 0, val29: 10 },
];

let sample1 = sample[0]; //<<-- you may loop through your entire array

for (const [key, value] of Object.entries(sample1)) {
  if (key.lastIndexOf('val')>=0 && value === 0){
       sample1[key] = null;
   }
}

console.log(sample1)

You can use this, but you need let to reuse the variable name

let sample = [
  { id: 1, val1: 0, val4: 10 },
  { id: 10, val1: 1, val4: 10, val19: 0, val29: 0 },
  { id: 11, val1: 0, val4: 0, val19: 0, val29: 10 },
];
sample = sample.map(obj => {
  Object.keys(obj).forEach(key => {
    obj[key] = obj[key] || null;
  });
  return obj;
});

console.log(sample)

This is basically getting the keys of each object then checking value of object against that key in obj[key] = obj[key] || null. So when obj[key] will be either 0, null or undefined, it will become equal to null, otherwise it won't update.

This is what Array.prototype.map was made for, it takes a function as a parameter, that is called once for each element of the array, while providing the element itself as an argument. The.map function returns a new set and does not directly modify the original. Whatever the return value is for the parameter function for each element is, becomes the new value of that element in the newly constructed array.

In your case though it is a bit more complicated since each element itself is an object, so we can convert each object to an array, map is own properties, and return the reconstructed object to our main .maps parameter function

So..

sample=sample.map(function (currentElement){
    return (typeof(currentElement) == "object" ?
        Object.fromEntries(
            Object.entries(
                currentElement
            ).map(function (prop){
                return prop === 0 ? null : prop
            })
        ) : currentElement
    )
})

I have an solution using map only, may help:

var sample = [
    { id: 1, val1: 0, val4: 10 },
    { id: 10, val1: 1, val4: 10, val19: 0, val29: 0 },
    { id: 11, val1: 0, val4: 0, val19: 0, val29: 10 },
  ]; 
var output = sample.map((item) => {
      Object.keys(item).map((key) => {
        item[key] = (item[key] == 0 ? null : item[key]); return item[key]
      });
      return item;
  });
  
  console.log(output);

You can use "for...in" to access every object

Demo Here

const sample = [
  { id: 1, val1: 0, val4: 10 },
  { id: 10, val1: 1, val4: 10, val19: 0, val29: 0 },
  { id: 11, val1: 0, val4: 0, val19: 0, val29: 10 },
];

sample.map((s) => {
  for (let i in s) if (s[i] === 0) s[i] = null;
  return s;
});
console.log(sample);

Immutable Style

const sample: Record<string, unknown>[] = [
  { id: 1, val1: 0, val4: 10 },
  { id: 10, val1: 1, val4: 10, val19: 0, val29: 0 },
  { id: 11, val1: 0, val4: 0, val19: 0, val29: 10 }
]

const updated = sample.map((rec) =>
  Object.keys(rec).reduce<Record<string, unknown>>(
    (acc, key) => (rec[key] == 0 ? { ...acc, [key]: null } : { ...acc, [key]: rec[key] }),
    {}
  )
)

console.log(updated)
// OUTPUT
// [
//   { id: 1, val1: null, val4: 10 },
//   { id: 10, val1: 1, val4: 10, val19: null, val29: null },
//   { id: 11, val1: null, val4: null, val19: null, val29: 10 }
// ]
Related