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.

1
  • 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. Commented Jul 27, 2018 at 16:04

2 Answers 2

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

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

2 Comments

Happy to help :)
it's not related but could you look at one of my other question stackoverflow.com/questions/51485838/… I am not getting any helpful replies on this. Thanks
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);

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.