简体   繁体   中英

Convert 2 arrays into key value object javascript

I have an array with headers - say ["language", "name", "code"] and an array of arrays of values - for example [["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]] .

I am trying to obtain an array of objects, like so:

[ 
  {language: English, name: Matt, code: 2D}, 
  {language: Croatian, name: Dana, code: 8S}, 
  {language: Russian, name: Ivan, code: 2W} 
]

Any elegant way to do this without nested for loops?

const props = ["language", "name", "code"];
const values = [["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]];
const formatted = values.map(value => ({
  [props[0]]: value[0],
  [props[1]]: value[1],
  [props[2]]: value[2],
}));

Or like this:

const formatted4 = values.map(value => {
  let v = {};
  props.forEach((prop, i) => {
    v = {
      ...v,
      [prop]: value[i]
    }
  });
  return v;
});

You can use array destructuring (assuming you're sure your data format stays the same) :

const newArr = [];
for(const [language, name, code] of yourDataArray){
  //do whatever you want with the variables language, name, code
  newArr.push({
    language: language,
    name: name,
    code: code
  })
}

 let props=["language", "name", "code"]; let data=[["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]]; let result=data.map( (innerArray) =>{let obj={};innerArray.forEach( (innerData,index) =>{obj[props[index]]=innerData;});return obj; }); console.log(result);

You can create this without complexity, if the data count is constant, using ES6*

var dataList = [["English", "Matt", "2D"], ["Croatian", "Dana", "8S"], ["Russian", "Ivan", "2W"]];
    let myList = [];
    for([language, name, code] of dataList)
      myList.push({language, name, code});
    console.log(myList);

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