如何将对象转换为数组?

时间:2019-06-06 22:33:01

标签: arrays json angular typescript

我有一个动态生成的对象。我需要获取该对象的某些字段(恰好是动态字段)并将其解析为数组。

在下面的代码中,我需要将塔[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]: ""
}

我希望它类似于:

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

还有一个新的数组,如:

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

3 个答案:

答案 0 :(得分:0)

只是猜测塔[0]会给出一个数字,如果可以,则可以这样做。这将找到所有具有布尔值的键,并保留它们并将它们附加到对象上。

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

答案 1 :(得分:0)

如果X = number并且obj是我们要转换的对象

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

答案 2 :(得分:0)

如果要变换对象数组,可以执行以下操作:

   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)
       }
    })

看到,地图允许一个“索引”(从0开始)

相关问题