如何将值作为键进行推送?

时间:2019-06-24 08:55:26

标签: javascript arrays object associative-array

我有JSON之类的

 0:{columnName:"gender",seedValues:["M","F"]}
 1:{columnName:"entity_type",seedValues:["O","I"]}

我想要JSON

{
  "gender":["M","F"],
  "entity_type":["O","I"]
 }

我尝试过

let value = this.values;
for(let i in value) {
    if(value[i].columnName=='gender')
    {
        this.gender.push(value[i].seedValues);
    }
    if(value[i].columnName=='entity_type')
    {
        this.entity.push(value[i].seedValues);
    }
    let obj = {
        "gender":this.gender,
        "entity_type":this.entity
    }
}

在Angular 6或JavaScript中,但是我想要这样的JSON结构

{
  "gender":["M","F"],
  "entity_type":["O","I"]
}

1 个答案:

答案 0 :(得分:0)

首先,这不是JSON,而是纯JS。其次,您可以使用reduce

const arr = [{columnName:"gender",seedValues:["M","F"]},{columnName:"entity_type",seedValues:["O","I"]}];
const res = arr.reduce((a, { columnName, seedValues }) => (a[columnName] = seedValues, a), {});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

或者,您可以根据键/值使数组中的每个项目成为自己的对象,然后reduce将它们组合在一起:

const arr = [{columnName:"gender",seedValues:["M","F"]},{columnName:"entity_type",seedValues:["O","I"]}];
const res = arr.map(({ columnName, seedValues }) => ({ [columnName]: seedValues })).reduce((a, c) => ({ ...a, ...c }));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }