0

I have data from a backend that I want to push to fields but I want to assign values to objectKey from the data object. Like [{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];
}

data from server

const data = [{
    assetPriority:"Normal",
    assetType:"Network Element",
    avgChargeAmt:"1200.00"
}];
CodeAt30
  • 874
  • 6
  • 17
hussain
  • 6,587
  • 18
  • 79
  • 152
  • 2
    Your question it's unclear. Can you edit your question to get a better understanding. – Ele Feb 02 '18 at 17:23
  • 1
    Your approach is only converting data's items to `undefined` because `this.fields[objectKey]` is not a valid way to access data from an array. Futher, `i` variable doesn't exist. – Ele Feb 02 '18 at 17:27
  • I guess you are looking for something like this: https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects – d4rty Feb 02 '18 at 17:41

1 Answers1

0

Sample Data array:

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

Building an object with info from data array:

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

With for loop:

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

Adapt this to your system.

CodeAt30
  • 874
  • 6
  • 17