【问题标题】:How can i join json objects and adding a new attribute inside ofHow can i join json objects and adding a new attribute inside of
【发布时间】:2022-12-02 04:19:26
【问题描述】:

I have some json objects, i want to join all of the objects only in one

i have this input

a:[{h:1, i:2}]
b:[{j:1, k:2}]
c:[{l:1, m:2}]

i need this output

[{type: a, h:1, i:2}, {type: a, o:1, p:2}, {type: b, j:1, k:2}, {type: c, l:1, m:2}]

i was trying:

const a = {"a":[{"h":1, "i":2}]}
const b = {"b":[{"j":1, "k":2}]}
const c = {"c":[{"l":1, "m":2}]}

const result = {};
let key;

for (key in a) {
  if(a.hasOwnProperty(key)){
    result[key] = a[key];
  }
}


for (key in b) {
  if(b.hasOwnProperty(key)){
    result[key] = b[key];
  }
}

console.log('b', result)

【问题讨论】:

    标签: javascript


    【解决方案1】:

    To combine the objects in thea,b, andcarrays into a single array, you can use themapandconcatmethods of the Array prototype. Themapmethod allows you to transform the elements in an array, and theconcatmethod allows you to merge two arrays into one.

    Here's an example of how you could use these methods to combine the objects in youra,b, andcarrays into a single array:

    const a = [{h: 1, i: 2}];
    const b = [{j: 1, k: 2}];
    const c = [{l: 1, m: 2}];
    
    const result = [].concat(
      a.map(obj => Object.assign({type: "a"}, obj)),
      b.map(obj => Object.assign({type: "b"}, obj)),
      c.map(obj => Object.assign({type: "c"}, obj))
    );
    

    After running this code, theresultarray will contain the combined objects from thea,b, andcarrays, with thetypeproperty added to each object. The output will look like this:

    [
      {type: "a", h: 1, i: 2},
      {type: "b", j: 1, k: 2},
      {type: "c", l: 1, m: 2}
    ]
    

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-02
      • 2021-07-18
      • 2022-12-02
      • 2022-12-01
      • 2022-12-27
      • 2022-12-01
      • 2019-07-14
      • 2022-12-02
      相关资源
      最近更新 更多