如何使用Jquery的Javascript从不同格式的嵌套JSON中提取值?

时间:2018-04-14 20:54:51

标签: javascript jquery json

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"
 }
 ]
 }
 ];

任何人都可以帮助我获得" id"价值和" pricetag"来自上面的JSON的值?它是嵌套的,可以采用不同的格式。但在每一个中,我需要提取id值和pricetag值。我尝试了很多东西但没有得到确切的输出。有人可以帮帮我吗 ?抱歉格式不好..

2 个答案:

答案 0 :(得分:1)

使用.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)

答案 1 :(得分:1)

这应该适合你:

wb = cv2.xphoto.createGrayworldWB()
wb.setSaturationThreshold(0.99)
image = wb.balanceWhite(image)

示例输出:

   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);