简体   繁体   中英

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?

You can use " Array.map " for this

 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

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

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