简体   繁体   English

在javascript中按值类型将嵌套数组对象更改为对象

[英]change nested array object to objects by value type in javascript

How to modify the array object to object in javascript.如何在javascript中将数组对象修改为对象。

I have object obj1 , change the value of details key to new object javascript我有对象obj1 ,将 details 键的值更改为新对象 javascript

function newObj(obj1){
  return Object.assign({}, ...obj1.map(e=>(e.details)));
}
var r1= this.newObj(obj1)

var obj1 = [
  {
    details: {
      "info":["stocks","finance",""],
      "sales":["analytics"]
    }
  }
]

var obj2 = [
  {
    details: {
      "city":{"SG"}
    }
  }
]
Expected Output
//for obj1 (show only first value of array)
{
  stocks: "stocks",
  analytics: "analytics"
}
//obj2
{
SG: "SG"
}

The object in obj2 should have keys. obj2的对象应该有键。

To solve this problem, we need to keep an object/map to fill it with the values to be returned by the function.为了解决这个问题,我们需要保留一个对象/映射来填充函数要返回的值。 Therefore, you need to iterate over each detail element and get the values of each property.因此,您需要遍历每个detail元素并获取每个属性的值。 Then, we can check whether it's an array or object and fill the map accordingly:然后,我们可以检查它是array还是object并相应地填充map

 var obj1 = [ { details: { "info":["stocks","finance",""], "sales":["analytics"] } } ] var obj2 = [ { details: { "city":{name:"SG"} } } ] function newObj(obj1){ let map = {}; obj1.forEach(e=>{ let details = e.details; Object.values(details).forEach(value => { if(Array.isArray(value) && value.length>0) map[value[0]]=value[0]; else if(typeof value === 'object') Object.values(value).forEach(val => { map[val]=val; }); }) }); return map; } var r1= this.newObj(obj1) console.log(r1); var r2 = this.newObj(obj2) console.log(r2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM