1

Am trying to add a new field (sid) in each object in a JavaScript array:

dataset_sk_final = [
  {'id':0,'name':'Banking'},
  {'id':1,'name':'Home'},
  {'id':2,'name':'Travel'}
]

My output should be like -

dataset_sk_final = [
  {'id':0,'name':'Banking','sid':''},
  {'id':1,'name':'Home','sid':''},
  {'id':2,'name':'Travel','sid':''}
]

I tried using below code but its not working, what am I missing?

var dataset_sk_final1 = [];
object.keys(dataset_sk_final).foreach(function (key) {
  'sid' = ''
}
dataset_sk_final1.push(dataset_sk_final[key]);

alert('after assigning final:'+json.stringify(dataset_sk_final1),null,2);
1
  • What does your console show? First, it will error out on object.keys, which needs to be Object.keys. Second, it will error out on 'sid'='', which is invalid syntax and doesn't mean anything--what did you expect that to do? Third, it will error out on the push line, since you are referring to key, which does not exist in this scope. Also, not that this problem has nothing to do with JSON. It's just a plain old JavaScript object. Commented Dec 10, 2015 at 19:00

2 Answers 2

1

First off in Array object there is no method foreach but there is forEach (case sensitive), second - to assign new property to Object you can use dot notation like el.sid = '' or bracket notation like el['sid'] = '' but not 'sid'='' because it is just String

var dataset_sk_final = [
  {'id':0,'name':'Banking'},
  {'id':1,'name':'Home'},
  {'id':2,'name':'Travel'}
];

dataset_sk_final.forEach(function (el) {
  el.sid = '';
});

console.log(JSON.stringify(dataset_sk_final, null, 2));

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

Comments

0

This should work?

for(var index in data_sk_final) {
    data_sk_final[index].sid = ''
}

so your example becomes

dataset_sk_final = [
  {'id':0,'name':'Banking'},
  {'id':1,'name':'Home'},
  {'id':2,'name':'Travel'}
]

for(var index in data_sk_final) {
    data_sk_final[index].sid = ''
}

alert('after assigning final:'+json.stringify(dataset_sk_final),null,2);

1 Comment

Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

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.