如何为现有阵列分配密钥?

时间:2018-02-02 17:19:11

标签: javascript arrays angularjs

我有来自后端的数据,我想推送到fields,但我想从数据对象中为objectKey分配值。与[{objectkey:"Normal"},{objectKey:"Network Element"}]

一样

main.js

this.fields = [{
  name: 'Ticket Number',
  objectKey: 'ticketNum',
  click: (row) => {this.rowData(row);}
},{
  name:'Ticket Opened',
  objectKey:'ticketOpened',
  click: (row) => {this.rowData(row);}
}]

data.forEach(function(item){
  item[i] = this.fields[objectKey];
}

来自服务器的数据

const data = [{
    assetPriority:"Normal",
    assetType:"Network Element",
    avgChargeAmt:"1200.00"
}];

1 个答案:

答案 0 :(得分:0)

示例数据数组:

const data =[{
  assetPriority: "Normal",
  assetType: "Network Element",
  avgChargeAmt:"1200.00"
}];

使用数据数组中的信息构建对象:

const fields = {
    objectKey1: data[0].assetPriority,
    objectKey2: data[0].assetType,
    objectKey3: data[0].avgChargeAmt
};

使用for循环:

let fieldsWithLoop = [];

for(let i = 0 ; i<data.length ; i++){
    let keys = Object.keys(data[i]);
    let objectToPush = {};

    for(let j = 0; j<keys.length;j++){
        objectToPush[keys[j]] = data[i][keys[j]];
    }

    fieldsWithLoop.push(objectToPush);
}

使其适应您的系统。