1

I have 2 arrays that i want to "reduce" into 1 object.

so for instance:

I have..

var originalData = [1,2,3];

var newData = [3,1,2];

i want to combine these two arrays into an object that looks like this:

var newOrderObject = {1:3, 2:1, 3:2};

im using a reduce function but it seems to be mapping them differently

var newOrderObject = originalData.reduce(function(newData) {
  var orderObject = {};
  originalData = newData;
  return orderObject;
}, {});

any suggests would be appretiated

Charlie Schliesser
  • 7,851
  • 4
  • 46
  • 76
zomdar
  • 263
  • 2
  • 6
  • 22
  • Have you tried this? https://stackoverflow.com/questions/10623635/combine-2-arrays-into-a-multidimensional-array – Pietro Nadalini Jan 11 '19 at 21:21
  • i'd like to merge into an object...i dont think that i can use push() right? – zomdar Jan 11 '19 at 21:22
  • Possible duplicate of [Creating a JavaScript Object from two arrays](https://stackoverflow.com/questions/39127989/creating-a-javascript-object-from-two-arrays) – Pietro Nadalini Jan 11 '19 at 21:27

3 Answers3

6

Reduce the 1st array (the keys), and take the values from the 2nd array using the index:

var originalData = [1,2,3];
var newData = [3,1,2];

var newOrderObject = originalData.reduce(function(obj, key, index) {
  obj[key] = newData[index];
  return obj;
}, {});

console.log(newOrderObject);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
3

You could map single objects and assign them to a single object. If empty arrays are possible, use an empty object as target value.

var keys = [1, 2, 3],
    values = [3, 1, 2],
    object = Object.assign({}, ...keys.map((k, i) => ({ [k]: values[i] })));

console.log(object);

A more cleaner approach would be to transpose the arrays to an array of key/value pairs and then map object.

const transpose = (r, a) => a.map((v, i) => (r[i] || []).concat(v));

var keys = [1, 2, 3],
    values = [3, 1, 2],
    object = Object.assign(
        {},
        ...[keys, values]
            .reduce(transpose, [])
            .map(([k, v]) => ({ [k]: v }))
    );

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

You're just using .reduce wrong.

  • The 1st argument of it's callback is the accumulator object you pass.
  • The 2nd is the currently iterated item.
  • The 3rd is the index.

Use all 3 and you get the result you want.

var originalData = [1,2,3];
var newData = [3,1,2];

var newOrderObject = originalData.reduce(function(acc, item, i) {
  return Object.assign(acc, { [item]: newData[i] })
}, {});

console.log(newOrderObject)
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167