Assigning key's to array objects

Viewed 337

I'm trying to solve this problem. Essentially, I have a array of keys, and an array of values within objects, and I want those values to have keys.

Below is my best attempt so far - usually use python so this is a bit confusing for me.

var numbers = [3, 4, 5,6]

var selection = [[1, 2, 3, 4], [6, 5, 4, 3], [2, 9, 4]]
var result = [];

for (arr in selection) {
numbers.forEach(function (k, i) {
result[k] = arr[i]
})
};

console.log(result);

The output I'm looking for is like this,

results = [{3:1,4:2,5:3,6:4}, {..},..]

Love some pointers to getting the right output.

Note. This is for google appscript! So can't use certain javascript functions (MAP I think doesn't work, unsure of reduce).

Cheers!

3 Answers

Create a separate function which take keys and values as arguments and convert it into object using reduce(). Then apply map() on selections and make an object for each subarray using that function

var numbers = [3, 4, 5,6]
var selection = [[1, 2, 3, 4], [6, 5, 4, 3], [2, 9, 4]]

function makeObject(keys, values){
  return keys.reduce((obj, key, i) => ({...obj, [key]: values[i]}),{});
}
const res = selection.map(x => makeObject(numbers, x));
console.log(res)

Use map on selection and Object.assign

var numbers = [3, 4, 5, 6];

var selection = [
  [1, 2, 3, 4],
  [6, 5, 4, 3],
  [2, 9, 4]
];

var result = selection.map(arr =>
  Object.assign({}, ...arr.map((x, i) => ({ [numbers[i]]: x })))
);

console.log(result);

Create a new object from scratch for each number array:

const selection = [
  [1, 2, 3, 4],
  [6, 5, 4, 3],
  [2, 9, 4],
];

function objMaker(numarr) {
  const numbers = [3, 4, 5, 6];
  numarr.forEach((num, i) => (this[numbers[i]] = num));
}
console.info(selection.map(numarr => new objMaker(numarr)));

Related