我试图从外部json文件获取值并在数组中保存一些值。我的代码:
$.getJSON("https://link.to.my.json", function(data) {
console.log(data); // this will show the info it in console
});
所以我可以从json获取数据,但我不知道如何在数组[bob rooppo,peter sticker]中添加名字和姓氏。任何帮助,将不胜感激 和我的json:
{
"users": [
{
"test": "123",
"name": {
"first": "bob",
"last": "roppo"
},
"email": "bob@gmail.com",
"phone": "+123456789"
},
{
"test": "124",
"name": {
"first": "peter",
"last": "sticer"
},
"email": "peter@gmail.com",
"phone": "+123456789"
}
]
}
答案 0 :(得分:2)
您只需使用Array#map
:
data.users.map(e =>
(e.name.first ? e.name.first : '') + //Handles the first name
(e.name.first ? ' ' : '') + //Space between the names
(e.name.last ? e.name.last : '') //Handles the last name
);
<强>演示:强>
const data = {
"users": [
{
"test": "123",
"name": {
"first": "bob",
"last": "roppo"
},
"email": "bob@gmail.com",
"phone": "+123456789"
},
{
"test": "124",
"name": {
"first": "peter",
"last": "sticer"
},
"email": "peter@gmail.com",
"phone": "+123456789"
}
]
};
let result = data.users.map(e => (e.name.first ? e.name.first : '') + (e.name.first ? ' ' : '') + (e.name.last ? e.name.last : ''));
console.log(result);
答案 1 :(得分:0)
您可以使用map
data.users.map( s => ( s.name.first || "" ) + " " + ( s.name.last || "" ) );
如果两个属性值始终存在,则不需要短路
data.users.map( s => s.name.first + " " +s.name.last );
<强>演示强>
var data = {
"users": [
{
"test": "123",
"name": {
"first": "bob",
"last": "roppo"
},
"email": "bob@gmail.com",
"phone": "+123456789"
},
{
"test": "124",
"name": {
"first": "peter",
"last": "sticer"
},
"email": "peter@gmail.com",
"phone": "+123456789"
}
]
};
var output = data.users.map( s => s.name.first + " " + s.name.last );
console.log(output);
&#13;
答案 2 :(得分:0)
您可以使用forEach()
:
var json = {
"users": [
{
"test": "123",
"name": {
"first": "bob",
"last": "roppo"
},
"email": "bob@gmail.com",
"phone": "+123456789"
},
{
"test": "124",
"name": {
"first": "peter",
"last": "sticer"
},
"email": "peter@gmail.com",
"phone": "+123456789"
}
]
}
var res = [];
json.users.forEach(function(p){
var name = p.name.first + ' ' + p.name.last;
res.push(name);
});
console.log(res);
&#13;