[英]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"
}
]
}
];
Can anyone help me to get the "id" value and "pricetag" value from the above JSON ? 谁能帮助我从上述JSON获取“ id”值和“ pricetag”值? It is nested one and can be in different format.
它是嵌套的,可以采用不同的格式。 But in each, i need to extract id value and pricetag value.
但是在每一个中,我需要提取id值和pricetag值。 I tried so many things but not getting exact output.
我尝试了很多事情,但没有得到确切的输出。 Can someone please help me ?
有人可以帮帮我吗 ? Sorry for the bad formatting ..
对不起,格式错误。
use .map()
to iterate and return the desired keys : 使用
.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)
This should work for you : 这应该为您工作:
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);
Sample output: 样本输出:
[ { pricetag: 'false', id: 1234 },
{ pricetag: 'true', id: 345787 },
{ pricetag: 'disabled', id: 86787876 } ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.