Tyler Morales
Tyler Morales

Reputation: 1848

How to combine two arrays into multiple objects with data from each array?

I am trying to resolve two arrays of length n into n objects with the same number of key value pairs as there are arrays. Each object should have a dynamic name key that correlates to the object's position.

For example, if there are 10 items in each array, there should be 10 objects and each objects should have a name key the is sequential --> Day[n]

The input will look like this:

// input
const temperatures: [65, 33]
const rain: [3, 8]

The output shape should look something like this:

// output
[
  {
    name: 'Day1',
    temperature: 65,
    rain: 3
  },
  {
    name: 'Day2',
    temperature: 33,
    rain: 8
  },
]

I've tried mapping through each array and creating an object for each array item and then combining them into one array of objects, but for some reasson, the results array only includes one set of the array names.

This is my code so far:

const temperature = [65, 33];
const rain = [3, 8];
const days = { name: 'Day1' };

const data1 = temperature.map((val) => {
  return { temperature: val };
});

const data2 = rain.map((val) => {
  return { rain: val };
});

const total = { ...days, ...data1, ...data2 };

console.log(total);

// output: { '0': { temperature: 65 }, '1': { temperature: 33 }, name: 'Day1' }

NOTE: I am creating the input arrays, so if there is any data I need to add or make changes to, that is a possibility.

Upvotes: 0

Views: 163

Answers (5)

Rahul Kumar
Rahul Kumar

Reputation: 3157

Create a function which accepts temperature and rain as parameter and returns the final result. Here we assume that both temperature and rain array are of same length.

const temperature = [65, 33];
const rain = [3, 8];

function convertArray(temperature, rain) {
    const result = [];
    for (let i = 0; i < rain.length; i++) {
        const weather = {
            name: `Day${i + 1}`,
            temperature: temperature[i],
            rain: rain[i]
        }
        result.push(weather)
    }
    return result;
}

console.log(convertArray(temperature, rain));

Upvotes: 0

Your use case does not require the use of the map() function.

I assume that, both the arrays temperature and rain always have the same number of elements. That is, if temperature array has temperature data for 3 Days then, even the rain array should have rain data for 3 Days

By taking the above assumption, We can loop over the elements of temperature array and insert a single object for each day into a new and final array which is your expected output.

We will use the every() function to achieve out goal:

var finalArray = [];

temperature.every((element, index) => {
    finalArray.push({
        name: `Day ${index}`, //Use index+1 for Day 1 and not Day 0
        temperature: element,
        rain: rain[index]
    });
});

console.log(finalArray); //The output

Upvotes: 0

Other Me
Other Me

Reputation: 508

const temperature = [65, 33];
const rain = [3, 8]; 
const length = Math.max(temperature.length, rain.length);

const output = [];

for(let i = 0; i < length; i++) {
  output.push({rain:rain[i], temperature:temperature[i], name:`Day${i+1}`});
}

Upvotes: 1

Braiden Cutforth
Braiden Cutforth

Reputation: 308

Assuming the input arrays are of the same size, one possible way of doing this would be the following:

const result = temperature.map((temp, index) => {
    return { name: `Day${index+1}`, temperature: temp, rain: rain[index] };
};

Although personally I don't think this is the cleanest or clearest way, and it may be worth considering changing the input types.

Upvotes: 0

Mister Jojo
Mister Jojo

Reputation: 22361

const 
  temperatures = [ 65, 33 ]
, rain         = [  3,  8 ]
, output = temperatures.map((t,i) =>
     ( { name        : `day${i+1}`
       , temperature : t
       , rain        : rain[i] 
     }))
;
console.log( output )
.as-console-wrapper {max-height: 100%!important;top:0;}

Upvotes: 0

Related Questions