![](/img/trans.png)
[英]How to create two arrays with different values in them from a JSON object?
[英]Create a JSON object from two distinct arrays
我有两个长度相同且与索引相关的数据数组。
var a = [ "Paris", "London", "Boston"];
var b = [ 70,60,50];
我想获得以下对象:
[{
"city":"Paris",
"temperature":70
},{
"city":"London",
"temperature":60
},{
"city":"Boston",
"temperature":50
}]
如何使用JavaScript实现此目标?
您可以为此使用“ Array.map ”
var a = [ "Paris", "London", "Boston"]; var b = [ 70,60,50]; let result = a.map((city, i) => ({ city, temperature: b[i] })) console.log(result)
为了获得预期的结果,请使用下面的选项(假设两个数组的长度相同)
var a = [ "Paris", "London", "Boston"]; var b = [ 70,60,50]; var result = []; a.forEach((v, i) =>{ result.push({city: v, temperature: b[i]}) }) console.log(result)
codepen- https: //codepen.io/nagasai/pen/gQWpxj
该解决方案通过避免使用硬编码属性来使用其他方法。
您可以通过迭代对象的条目来获取一个对象并构建一个对象数组。 这种方法适用于任意数量的属性。
var city = ["Paris", "London", "Boston"], temperature = [70, 60, 50], data = { city, temperature }, result = Object .entries(data) .reduce((r, [k, a]) => a.map((v, i) => Object.assign(r[i] || {}, { [k]: v })), []); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.