简体   繁体   中英

How can I replace values of Javascript Object with different values?

I'm looking for replacing the initial values of myObject by renamed names:

let myObject = 
  [ { name: 'X0', values: 'FALSE,TRUE'      } 
  , { name: 'X1', values: 'NORMAL,LOW,HIGH' } 
  , { name: 'X2', values: 'HIGH,NORMAL,LOW' } 
  , { name: 'X3', values: 'FALSE,TRUE'      } 
  ]     

I have two arrays: arr1 contains all the unique values of myObject . arr2 contains all the unique values renamed in which the values of myObject should be replaced.
As you can notice, they are already in the right order:
it means FALSE goes to JDIFS , LOW to T9SQK and so on.

let arr1 = ['FALSE', 'TRUE',  'NORMAL', 'LOW',   'HIGH'  ]
let arr2 = ['JDIFS', 'CZ899', 'YVI0T',  'T9WQK', '0XCH7' ]

Output expected:

let expected = 
  [ { name: 'X0', values: 'JDIFS,CZ899'        } 
  , { name: 'X1', values: 'YVIOT,TW9WQK,0XCH7' } 
  , { name: 'X2', values: '0XCH7,YVIOT,T9WQK'  } 
  , { name: 'X3', values: 'JDIFS,CZ899'        } 
  ] 

I wanted to loop over the object like this:

let second_column = myObject["columns"][1] 
for (let i=0; i< myObject.length; i++) {
  let tran = myObject[i][second_column].split(',') 
  // and perform and exchange with the two arrays I already have, or with the replace method
}

you can try:

 const myObject = [{"name":"X0","values":"FALSE,TRUE"},{"name":"X1","values":"NORMAL,LOW,HIGH"},{"name":"X2","values":"HIGH,NORMAL,LOW"},{"name":"X3","values":"FALSE,TRUE"}]; const arr1 = ["FALSE", "TRUE", "NORMAL", "LOW", "HIGH"]; const arr2 = ["JDIFS", "CZ899", "YVI0T", "T9WQK", "0XCH7"] const result = myObject.map( i => { const data = i.values.split(',').map(val => arr2[arr1.indexOf(val)]); return {...i, values: data.join(',') } }) console.log(result)

i.values.split(','): "FALSE,TRUE" => ["FALSE","TRUE"]

arr2[arr1.indexOf(val)]: return value by index

Try:

let myObject = [
  { name: 'X0', values: 'FALSE,TRUE' },
  { name: 'X1', values: 'NORMAL,LOW,HIGH' },
  { name: 'X2', values: 'HIGH,NORMAL,LOW' },
  { name: 'X3', values: 'FALSE,TRUE' },
];

const arr1 = ['FALSE', 'TRUE', 'NORMAL', 'LOW', 'HIGH'];
const arr2 = ['JDIFS', 'CZ899', 'YVI0T', 'T9WQK', '0XCH7'];

for (let i = 0; i < myObject.length; i++) {
  let tran = myObject[i].values;
  for (let j = 0; j < arr1.length; j++) {
    tran = tran.replace(arr1[j], arr2[j]);
  }
  myObject[i].values = tran;
}

console.log("OUTPUT:", myObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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