jeebee
jeebee

Reputation: 21

add new fieds in Json array

i would like to update a json object

let's say that my json object is (the variable is for testing purpose, in reality i receive json from api)

var json = [
    {
        user: "value1",
        country: "value2",
        name: "value3"
    }
]

now with javascript or jquery, i want to add for example the following fields

firstname: "value" 

so my final json should be

[
    {
        user: "value1", 
        country: "value2", 
        name: "value3", 
        firstname: "value"
    }
]

i've tried everything found in Stack overflow

json["firstname"] = "value"

or

jquery.extend 

or

json.push 

but this doesnt update my json variable or put me data outsier the ()

any suggestion ?

Upvotes: 0

Views: 47

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Since the object is inside the array you need to use json[0]["firstname"] = "value", json[0] will retrieve first element from array which is the object

var json = [{
  user: "value1",
  country: "value2",
  name: "value3"
}]
json[0]["firstname"] = "value";

document.write('<pre>' + JSON.stringify(json,null,3) + '</pre>');


If array contains multiple elements then iterate over them and add property, You can use map() for that

var json = [{
  user: "value1",
  country: "value2",
  name: "value3"
}, {
  user: "valude1ds",
  country: "valuesds2",
  name: "valdsdsue3"
}]
json = json.map(function(v) {
  v["firstname"] = "value";
  return v;
});

document.write('<pre>' + JSON.stringify(json, null, 3) + '</pre>');

Upvotes: 1

undefined_variable
undefined_variable

Reputation: 6228

$.each(json,function(key,value){
     json[key]["firstname"] = "value";
});

Above code will add firstname to all the objects in the json array

Upvotes: 0

Related Questions