简体   繁体   English

如何使用2个数组创建具有键和值的新数组?

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

I have 2 array, one for key and other for value . 我有2个数组,一个用于key ,另一个用于value

Want create new array with these arrays. 想要使用这些数组创建新数组。

key: [01, 02, 03] 关键: [01, 02, 03]
value: ["hi", "hello", "welcome"] 价值: ["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: 还有一个针对Object的以下方法的提议, fromEntries ,它将完全按照您的意愿执行,但主流浏览器尚不支持它:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries 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() : 在这里你有另一个使用reduce()的 apporach:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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