[英]How to extract values from nested JSON with different formatting using Javascript of Jquery?
var cart =
[
{
"Items": "",
"category": "",
"contents":
[
{
"Apple iPhone": "222",
"French": "Bounjour",
"id": 1234,
"icon": "/images/bg.jpg",
"callback": "use()",
"pricetag":"false"
}
]
},
{
"Items": "No 2",
"category": "2nd",
"contents":
[
{
"redmi": "333",
"French": "some text",
"id": 345787,
"icon": "/images/bg.jpg",
"callback": "use()",
"pricetag":"true"
},
{
"samsung": "333",
"French": "some text",
"id": 86787876,
"icon": "/images/bg.jpg",
"callback": "use()",
"pricetag":"disabled"
}
]
}
];
誰能幫助我從上述JSON獲取“ id”值和“ pricetag”值? 它是嵌套的,可以采用不同的格式。 但是在每一個中,我需要提取id值和pricetag值。 我嘗試了很多事情,但沒有得到確切的輸出。 有人可以幫幫我嗎 ? 對不起,格式錯誤。
使用.map()
進行迭代並返回所需的鍵:
var cart = [{ "Items": "", "category": "", "contents": [{ "Apple iPhone": "222", "French": "Bounjour", "id": 1234, "icon": "/images/bg.jpg", "callback": "use()", "pricetag": "false" }] }, { "Items": "No 2", "category": "2nd", "contents": [{ "redmi": "333", "French": "some text", "id": 345787, "icon": "/images/bg.jpg", "callback": "use()", "pricetag": "true" }, { "samsung": "333", "French": "some text", "id": 86787876, "icon": "/images/bg.jpg", "callback": "use()", "pricetag": "disabled" } ] } ]; let values = cart.map((e) => { return e.contents.map((a) => { return { id: a.id, pricetag: a.pricetag } }) }) console.log(values)
這應該為您工作:
var items=[];
var some_var;
const map1 = cart.map(function(item){
const map2=item.contents.map(function(contentItem){
//some_var=contentItem.id;
return{
pricetag:contentItem.pricetag,
id:contentItem.id
}
})
items=items.concat(map2)
});
console.log(items);
樣本輸出:
[ { pricetag: 'false', id: 1234 },
{ pricetag: 'true', id: 345787 },
{ pricetag: 'disabled', id: 86787876 } ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.