1

I have a json array as:

  0: {Id: "1", name: "Adam", Address: "123", userId: "i98"}
  1: {Id: "2", name: "John", Address: "456"}

Now in the above array, the second one has no userId key available.

How can I loop through the above array and check if no userId key available then add the key with value 0. For eg add userId: "0"

What I have tried is the following:

let jsonData = JSON.parse(JSON.stringify(userData));

 for (const obj of jsonData) {
    var hasId = false;
      let objId = obj.find((o, i) => {
         if (o.userId === "userId") {
          hasId = true;
        }
      });
      if (!hasId) {
         obj.push();
       }
    }

But this gives me error:

obj.find is not a function

Any inputs to resolve my issue and push the key value to the array.

user1563677
  • 713
  • 3
  • 15
  • 38
  • 2
    _"I have a json array"_ - No, that's an array of objects. JSON is a textual, language-indepedent data-exchange format, much like XML, CSV or YAML. – Andreas Jul 27 '18 at 16:04

2 Answers2

3

On your code, obj is an object and there is no find method on objects. If you want to check if an object has an array you can just if( obj.userId )

You can use forEach to loop thru the array.

let jsonData  = [{Id: "1", name: "Adam", Address: "123", userId: "i98"},{Id: "2", name: "John", Address: "456"}];

jsonData.forEach(o => {
  o.userId = o.userId || 0; //Assign 0 if userId is undefined.
})

console.log(jsonData);
Eddie
  • 26,593
  • 6
  • 36
  • 58
  • Happy to help :) – Eddie Jul 27 '18 at 17:21
  • it's not related but could you look at one of my other question https://stackoverflow.com/questions/51485838/angularjs-required-field-validation-and-highlight-for-dynamic-rows-of-html-tabl?noredirect=1#comment90010525_51485838 I am not getting any helpful replies on this. Thanks – user1563677 Jul 27 '18 at 21:17
2

You can make use of Array.prototype.map() and Object.prototype.hasOwnProperty() like the following way:

var jsonData = [{Id: "1", name: "Adam", Address: "123", userId: "i98"},{Id: "2", name: "John", Address: "456"}]

jsonData = jsonData.map(i => {
  if(!i.hasOwnProperty('userId'))
    i.userId = 0;
  return i;
});

console.log(jsonData);
Mamun
  • 66,969
  • 9
  • 47
  • 59