【问题标题】:Is there a way to append a json object into another json abject in react?有没有办法在反应中将一个 json 对象附加到另一个 json 对象中?
【发布时间】:2021-02-07 12:03:30
【问题描述】:

reactjs中如何将一个json对象追加到另一个json对象中?

我从控制台获取的 json 格式如下

Json 1:

{
 "results": {
             "Action": "Success!"
 },
 "report": {
             "Strategy": "Yes",
             "Plan": "No"
  }
}

Json 2:

{
     "results": {
                 "Actions": "Failure!"
     },
     "report": {
                 "Idea": "Yep",
                 "Storm": "Nope"
      }
 }

附加 JSON(所需的输出格式):

{
     "results": {
                 "Action": "Success!",
                 "Actions": "Failure!"
     },
     "report": {
                 "Strategy": "Yes",
                 "Plan": "No",
                 "Idea": "Yep",
                 "Storm": "Nope"
      }
}

【问题讨论】:

  • 为什么要创建一个有两个相似键的对象?我猜它应该是对象数组。有人解析您的 JSON 的那一刻,重复的键将被合并。
  • 我已经编辑了我的问题,我是新来的反应,这就是为什么我不能准确地传达它。

标签: arrays json reactjs object append


【解决方案1】:

键不能重复,这就是为什么我认为这不是合并两个对象的正确方法。 如果您尝试合并 last(latest) 将替换以前的字段(键)。

如果你想要你提到的输出。在这种情况下,您需要更改键字段名称。

JavaScript 对象不能有重复的键。键都必须是唯一的。

改进

let obj1 = {
 "results": {
      "Action": "Success!"
 },
 "report": {
       "Strategy": "Yes",
       "Plan": "No"
  }
}
let obj2 = {
     "results": {
        "Action": "Failure!"
     },
     "report": {
         "Strategy": "Yep",
         "Plan": "Nope"
      }
 }
 
 let res = {
  results:{...obj1.results, ...obj2.results}, 
  report: {...obj1.report, ...obj2.report}
  };
 console.log(res)

【讨论】:

    【解决方案2】:

    你可以组合两个对象

    const json1 = {
      "results": {
        "Action": "Success!"
      },
      "report": {
        "Strategy": "Yes",
        "Plan": "No"
      }
    };
    
    const json2 = {
      "results": {
        "Actions": "Failure!"
      },
      "report": {
        "Idea": "Yep",
        "Storm": "Nope"
      }
    };
    
    let res = Object.keys(json1).reduce((a, key) => {
      a[key] = { ...json2[key], ...json1[key] }
      return a
    }, {});
    
    console.log(res)
    

    【讨论】:

      【解决方案3】:

      您可以遍历对象并将其合并在一起。

      const firstJsonObject = JSON.parse(firstJson);
      const secondJsonObject = JSON.parse(secondJson);
      
      let res = {};
      
      Object.keys(firstJsonObject).forEach(key => {
        res[key] = { ...firstJson[key], ...secondJsonObject[key] };
      });
      
      console.log(JSON.stringify(res))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-18
        • 2016-03-31
        • 2012-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-26
        • 2011-04-15
        相关资源
        最近更新 更多