ldesigns
ldesigns

Reputation: 103

Add keys to arrays and then combine (Is there a better way?)

I currently have two arrays that I receive from an API that looks like this:

["Array1", "Array1", "Array1"]
["Array2", "Array2", "Array2"]

I want to add keys to them, so they look like this:

[{date: "Array1"}, {date: "Array1"}, {date: "Array1"}]
[{data: "Array2"}, {data: "Array2"}, {data: "Array2"}]

And then combine them to be this:

[
  {date: "Array1", data: "Array2"},
  {date: "Array1", data: "Array2"},
  {date: "Array1", data: "Array2"},
]

I think I've gotten what I want with this code:

var Array1 = ["Array1", "Array1", "Array1"];
var Array2 = ["Array2", "Array2", "Array2"];
var newArray1 = Array1.map((i) => ({
  date: i
}))
var newArray2 = Array2.map((i) => ({
  data: i
}))

var combined = [];
for (var i = 0; i < newArray1.length; i++) {
  combined.push({
    ...newArray1[i],
    ...newArray2[i]
  });
}

console.log(combined);

Is there a better way to do this?

Upvotes: 0

Views: 62

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386604

You could take a dynamic approach with an array for the keys and assign new properties by taking a value from the result set or a new object.

var data1 = ["Array1", "Array1", "Array1"],
    data2 = ["Array2", "Array2", "Array2"],
    keys = ["date", "data"],
    result = [data1, data2]
        .reduce((r, b, i) => b.map((v, j) => Object.assign(r[j] || {}, { [keys[i]]: v })), []);

console.log(result);

Upvotes: 0

Mikolaj Figurski
Mikolaj Figurski

Reputation: 153

You can perform the combination within array.map.

The documentation for Array.prototype.map() notes the following syntax:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

Note that the callback function can take not only current value but also index (and array, but you don't need that). You can use this to condense combination to the following:

Array1.map((elem, i) => ({ date: elem, data: Array2[i] }));

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

You can map Array1 to get the date, and get the data from Array2 by index:

var Array1 = ["Array1", "Array1", "Array1"];
var Array2 = ["Array2", "Array2", "Array2"];

var combined = Array1.map((date, i) => ({
  date,
  data: Array2[i]
}))

console.log(combined)

Upvotes: 3

Related Questions