0

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?

2
  • 3
    at least, you could add your try. Commented Nov 14, 2018 at 21:48
  • I would probably use the aray method - reduce. Commented Nov 14, 2018 at 21:49

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.