简体   繁体   中英

How to create new array with key and value with 2 arrays?

I have 2 array, one for key and other for value .

Want create new array with these arrays.

key: [01, 02, 03]
value: ["hi", "hello", "welcome"]
Output I need:

[ 
  {"key": "1","value":"hi"},
  {"key": "2","value":"hello"},
  {"key": "3","value":"welcome"} 
]    

How to get result by this way.?

My code:

output = key.map(function(obj, index){
      var myObj = {};
      myObj[value[index]] = obj;
      return myObj;
    })    

Result:

 [
 {"1","hi"},
 {"2","hello"},
 {"3","welcome"} 
    ]

 const keys = [01, 02, 03]; const values = ['hi', 'hello', 'welcome']; const res = keys.map((key, ind) => ({ 'key': ''+key, 'value': values[ind]})); console.log(res); 

There is also a proposal for the following method of Object, fromEntries , which will do exactly what you want to, but it is not supported yet by the major browsers:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

  var myArray = []; var keys = [45, 4, 9]; var cars = ["Saab", "Volvo", "BMW"]; cars.forEach(myFunction); var txt=JSON.stringify(myArray); document.getElementById("demo").innerHTML = txt; function myFunction(value,index,array) { var obj={ key : keys[index], value : value }; myArray.push(obj); } 
  <p id="demo"></p> 

You could take an object with arbitrary count of properties amd map new objects.

 var key = [1, 2, 3], value = ["hi", "hello", "welcome"], result = Object .entries({ key, value }) .reduce((r, [k, values]) => values.map((v, i) => Object.assign( {}, r[i], { [k]: v } )), []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Here you have another apporach using reduce() :

 let keys = [01, 02, 03]; let values = ['hi', 'hello', 'welcome']; let newArray = keys.reduce((res, curr, idx) => { res.push({'key': curr.toString(), 'value': values[idx]}); return res; }, []); console.log(newArray); 

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