I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'[email protected]',
'[email protected]',
'[email protected]']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'[email protected]',
'[email protected]',
'[email protected]']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
Share Improve this question asked Aug 2, 2016 at 4:29 user6665903user6665903 2-
1
That's a syntax error. Are you sure it's not an object that contains a
links
array? – slebetman Commented Aug 2, 2016 at 4:31 -
You probably meant to write
json_data = { ... }
– Sverri M. Olsen Commented Aug 2, 2016 at 4:31
3 Answers
Reset to default 5Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("[email protected]");
json_data.links.push("[email protected]");
json_data.links.push("[email protected]");
You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will bee JSON Literal - a key value pair.
Second thing, You have missed mas after 'name':'Testing'
and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'[email protected]',
'[email protected]',
'[email protected]']
}
In addition to push
as mentioned by @giovannilobitos you can use concat
and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'[email protected]',
'[email protected]',
'[email protected]'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more plete list of how to modify arrays in JavaScript.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745266259a4619474.html
评论列表(0条)