【问题标题】:JS: How to parse a nested JSON?JS:如何解析嵌套的 JSON?
【发布时间】:2021-06-17 05:39:36
【问题描述】:

有一个 JSON 对象:

var items = [{
              "item" : "A",
              "checked": false,
              "info": { "hello": "world" },
              "products": []
              },
              {
              "item" : "B",
              "checked": true,
              "info": { },
              "products": [1, 2, 3]
              }];

我需要解析每个嵌套对象,如果有其他对象,将它们转换为字符串。

例如,第一个对象有另一个对象进入“信息”键。并将修改后的 JSON Object 放入一个新的数组中。

我试过这样:

var modifiedObj = [];

        items.forEach(function(item) {
            //get only values
            var val = Object.values(item);
            val.forEach(function(el) {
                //only if value is an object
                if (typeof el === 'object' && !Array.isArray(el)) {
                    //convert to str
                    var str = JSON.stringify(el, null, 2);
                    console.log(str);
                }
            });
        });

它有效,但我不知道如何将修改后的 JSON 放入新数组中。所以我的理想结果是:

modifiedObj  = [{
              "item" : "A",
              "checked": false,
              "info": "{ 'hello': 'world' }", //String
              "products": []
              },
              {
              "item" : "B",
              "checked": true,
              "info": "{ }", //String
              "products": [1, 2, 3]
              }];

【问题讨论】:

  • 您只需要对对象的一部分进行字符串化吗?仅当 value 是一个对象而不是数组时?

标签: javascript arrays json object


【解决方案1】:

您可以使用.map() 遍历数组并返回一个新数组。 由于数组的元素是对象,因此您需要使用 for...in 循环来迭代对象。

var items = [{
    "item": "A",
    "checked": false,
    "info": {
      "hello": "world"
    },
    "products": []
  },
  {
    "item": "B",
    "checked": true,
    "info": {},
    "products": [1, 2, 3]
  }
];

const modObj = items.map(item => {
  for (let prop in item) {
    if(typeof item[prop] === 'object' && !Array.isArray(item[prop])) {
      item[prop] = JSON.stringify(item[prop])
    }
  }
  return item;
})

console.log({ modObj })

PS:我不确定您要对哪些属性进行字符串化,所以我在答案中保留了原始的 if 条件。

阅读更多关于for...inmap()的链接

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    相关资源
    最近更新 更多