简体   繁体   English

如何将对象转换为数组?

[英]How to transform object into array?

I have an object which is dynamically built. 我有一个动态构建的对象。 I need to get some of the fields of this object (exactly the dynamic ones) and parse them into an array. 我需要得到这个对象的一些字段(完全是动态的)并将它们解析成一个数组。

In the code below, I need to transform the towers[X] into an array of objects. 在下面的代码中,我需要将塔[X]转换为一个对象数组。

{id: "", description: "Teste", towers[1]: true, towers[2]: true, 
    towers[3]: true, …}
    description: "Test"
    id: ""
    towers[1]: true
    towers[2]: true
    towers[3]: true
    towers[4]: ""
}

I want it to be something like: 我希望它是这样的:

{
    id: ""
    description: "Test",
    towers[1]: true //Don't care if it stays here or not, will not use
    ...
}

And a new array like: 还有一个新的数组:

{
    [id: 1, value: true],
    [id: 2, value: true],
    [id: 3, value: true],
    [id: 4, value: ""]
}

Just going to guess towers[0] gives back a number, if it does you can do this. 只是猜猜塔[0]会给出一个数字,如果可以的话,你可以做到这一点。 This will find all keys that have boolean values and keep them and append them to a object. 这将找到具有布尔值的所有键并保留它们并将它们附加到对象。

const obj = YOUROBJHERE;
Object.keys(obj ).filter((key) => tyepof obj[key] === "boolean").reduce((accum, key) => {
    return {...accum, [key]: obj[key]};
}, {})

in case of X=number and obj is the object we want to transform 在X = number的情况下,obj是我们想要变换的对象

let result = [];
for (let indx = 1; indx <=x ; i++) {
result.push({value:indx,value: obj['towers'+indx]})
}

If you want to transform your array of object you can do some like: 如果要转换对象数组,可以执行以下操作:

   this.obj=this.obj.map(obj=>{
      return {
      id:obj.id,
      description:obj.description,
      towers:Object.keys(obj).filter((key) => key.indexOf('towers') != -1 )
          .map((k,index)=>{
              return {id:index+1,value:obj[k]}
          })
          .filter((x:any)=>x.value)
       }
    })

See that, map allow an "index" (begins by 0) 看到这一点,map允许一个“索引”(从0开始)

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

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