Reputation: 1854
How can i add "name_3" to this json?
json = {
"name_1": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
],
"name_2": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
]
}
var name_3 = {"kind": "audio","artistId": 4691754},{"kind": "video","artistId": 139918600}
i want to access it like this json.name_3[0]artistId
Later, i will have to check if it already exist and rewrite it, or delete it from a custom function
Upvotes: 0
Views: 44
Reputation: 27222
You can try spread operator to achieve this.
var json = {
"name_1": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
],
"name_2": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
]
};
var name_3 = [{"kind": "audio","artistId": 4691754},{"kind": "video","artistId": 139918600}];
console.log({...json, name_3});
Upvotes: 0
Reputation: 152
Your json has to be string not object, then you can parse it to object via JSON.parse() method. Then you can add your new element to object and make it json format again using JSON.stringify() method.
const json = `{
"name_1": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
],
"name_2": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
]
}`
const name3 = [{kind: "audio",artistId: 4691754},{kind: "video",artistId: 139918600}];
let obj = JSON.parse(json);
Object.assign(obj, name3);
const newJson = JSON.stringify(obj)
Upvotes: -1
Reputation: 79
let json = {
"name_1": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
],
"name_2": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
]
}
let name_3 = [{ "kind": "audio", "artistId": 4691754 }, { "kind": "video", "artistId": 139918600 }];
json["name_3"] = name_3;
//or
//json.name_3 = name_3;
//access it:
console.log(json.name_3 && json.name_3[0].artistId);
//check if it's there:
if (json.name_3) console.log("It's there");
else console.log("Not there")
//delete it:
delete json.name_3;
Upvotes: 1
Reputation: 206459
Use brackets json["name_3"] =
or with a variable json[name] =
or dot notation json.name_3 =
const json = {
"name_1": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
],
"name_2": [{
"kind": "podcast",
"artistId": 139918600
},
{
"kind": "podcast",
"artistId": 139918600
}
]
};
const name = "name_3";
json[name] = [{
"kind": "movie",
"artistId": 123456780
}];
console.log(json[name][0])
Upvotes: 1