解析嵌套的JSON数据

时间:2018-10-17 19:50:38

标签: javascript json

我是Java,ES6的新手,并且遇到了这个问题

这是我从Web服务获取的JSON

{
  "products": [
    {
      "id": 2,
      "id_default_image": "21",
      "price": "35.900000",
      "name": [
        {
          "id": "1",
          "value": "item 1"
        },
        {
          "id": "2",
          "value": "item 1 alternate name"
        }
      ]
    },
    {
      "id": 4,
      "id_default_image": "4",
      "price": "29.000000",
      "name": [
        {
          "id": "1",
          "value": "item 2"
        },
        {
          "id": "2",
          "value": "item 2 alternate name"
        }
      ]
    }
  ]
}

上述JSON中的name属性是一个数组,我只需要第一个元素的值。所需的输出如下所示

{
  "products": [
    {
      "id": 2,
      "id_default_image": "21",
      "price": "35.900000",
      "name": "item 1"
    },
    {
      "id": 4,
      "id_default_image": "4",
      "price": "29.000000",
      "name": "item 2"
    }
  ]
}

我正在做一个本机反应项目。实现这一目标的最简单方法是什么?任何帮助将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:1)

类似于Ele的答案,但是如果您不想更改原始对象。您可以使用map遍历产品对象并返回一个新的产品数组:

const data = {"products":[{"id":2,"id_default_image":"21","price":"35.900000","name":[{"id":"1","value":"item 1"},{"id":"2","value":"item 1 alternate name"}]},{"id":4,"id_default_image":"4","price":"29.000000","name":[{"id":"1","value":"item 2"},{"id":"2","value":"item 2 alternate name"}]}]};

const products = data.products.map(obj => ({ ...obj, name: obj.name[0].value }));

console.log(products);

也使用:spread syntax

答案 1 :(得分:0)

好吧,您可以使用函数forEach或简单的for-loop并将第一个值分配给属性name

let obj = {  "products": [    {      "id": 2,      "id_default_image": "21",      "price": "35.900000",      "name": [        {          "id": "1",          "value": "item 1"        },        {          "id": "2",          "value": "item 1 alternate name"        }      ]    },    {      "id": 4,      "id_default_image": "4",      "price": "29.000000",      "name": [        {          "id": "1",          "value": "item 2"        },        {          "id": "2",          "value": "item 2 alternate name"        }      ]    }  ]}

obj.products.forEach(o => (o.name = o.name[0].value));

console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

尝试一下

 const productsArray = products.map((product, index) => {
   const obj = {};
   obj["id"] = product["id"];
   obj["id_default_image"] = product["id_default_image"];
   obj["price"] = product["price"],
  obj["name"] = product.name[0].value;
  return obj;
});

 const obj = {};
 obj.products = productsArray;

 console.log(obj);//will print you the desired output you want