简体   繁体   English

从两个不同的数组创建一个JSON对象

[英]Create a JSON object from two distinct arrays

I have two Arrays of data with same length and indexes are related. 我有两个长度相同且与索引相关的数据数组。

var a = [ "Paris", "London", "Boston"];
var b = [ 70,60,50];

I want to obtain the following object: 我想获得以下对象:

[{
    "city":"Paris",
    "temperature":70
},{
    "city":"London",
    "temperature":60
},{
    "city":"Boston",
    "temperature":50
}]

How can I achieve this using javascript? 如何使用JavaScript实现此目标?

You can use " Array.map " for this 您可以为此使用“ 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) 

To achieve expected result, use below option (assuming both arrays of same length) 为了获得预期的结果,请使用下面的选项(假设两个数组的长度相同)

  1. Loop first array 循环第一个数组
  2. Assign each value with corresponding second array value into result array 将每个值和相应的第二个数组值分配给结果数组

 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 codepen- https: //codepen.io/nagasai/pen/gQWpxj

This solution uses a different approach by avoiding hard coded properties. 该解决方案通过避免使用硬编码属性来使用其他方法。

You could take an object and build an array of object by iterating the entries of the object. 您可以通过迭代对象的条目来获取一个对象并构建一个对象数组。 This approach works for an arbitrary count of properties. 这种方法适用于任意数量的属性。

 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.

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