admin管理员组文章数量:1417463
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.
本文标签: set array as value in json format in JavascriptStack Overflow
版权声明:本文标题:set array as value in json format in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745266258a2650619.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论