将一个json中的值推到另一个json中

时间:2017-10-10 10:24:01

标签: json angular typescript

我有2个不同的JSON对象

JSON1

 [
   {
     title: "Order Rule Violations",
     type: "FieldView",
     panel: "expanded",
     data: [      
       {
         label: "Rule Description",       
         type: "text",
       },
       {  
         label: "comments",       
         type: "inputarea",
       },
     ],
   },
 ]

JSON2

[
  {
    data: [
      {
        value: "00695",
      },
      {        
        value: " ",        
      },
    ],
  },
]

我需要结合并得到像

这样的结果
[
  {
    title: "Order Rule Violations",
    type: "FieldView",
    panel: "expanded",
    data: [
      {
        label: "Rule Description",       
        type: "text",
        value: "00695",
      },
      { 
        label: "comments",       
        type: "inputarea",
        value: " ",
      },
    ],
  },
]

请告知我如何使用Angular / Typescript

实现此目的

3 个答案:

答案 0 :(得分:0)

这适用于这种情况:

for(var i=0;i<JSON1[0].data.length;i++)
JSON1[0].data[i].value= JSON2[0].data[i].value;

答案 1 :(得分:0)

您可以使用嵌套的Object.assign迭代每个数组,然后合并这两个对象。

const json1 = [{
  title: 'Order Rule Violations',
  type: 'FieldView',
  panel: 'expanded',
  data: [{
      label: 'Rule Description',
      type: 'text',
    },
    {
      label: 'comments',
      type: 'inputarea',
    },
  ],
}];

const json2 = {
  data: [{
      value: '00695',
    },
    {
      value: ' ',
    },
  ]
};

const json3 = json1.map(y => {
  y.data = y.data.map(
      (x, index) => Object.assign(x, json2.data[index])
    );
  return y; 
 });
  
console.log(json3);

另一种解决方案是使用Lodash's _.merge function

答案 2 :(得分:0)

我改变JSON2有点像JSON2 = [&#34;&#34;,&#34;&#34;,&#34;&#34;,....]和下面的代码 为我工作,

[(^\\.)]+
[(.+\\.)]+
[^\\p{L}\\d]+