5

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.

2
  • by value do you mean val1, val2, etc...? Commented Sep 16, 2020 at 5:59
  • Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output using the [<>] snippet editor. Commented Sep 16, 2020 at 6:00

8 Answers 8

5

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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)

Comments

0

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.

2 Comments

I made you a snippet. I also removed the unnecessary spread [...] - lastly, you will set valx: "" to null too with your falsy shortcut. Otherwise shorter code than mine
@mplungjan thanks. I thought using Object.keys(obj) directly would not work, so I used the spread operator.
0

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
    )
})

4 Comments

No it is not necessarily what map was made for since map will return a NEW array and is not needed if you just want to modify the existing array, then that is what forEach was made for. Your code is very complex for a very simple task
@mplungjan ok how can it be simpler?
@mplugjan i see my own
sample.forEach(item => { for (val in item) item[val] = item[val] === 0 ? null : item[val] }); is simpler than yours no?
0

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);

4 Comments

This is identical to more than one other answer here
Agree, it's with a little different approach, right?
Yes, needless use of {} and () ;)
Yes I can remove
0

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);

2 Comments

Why use map and not forEach. You do not need the array map creates
You also do not need to return anything: sample.forEach(s => { for (let i in s) if (s[i] === 0) s[i] = null; });
0

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 }
// ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.