Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning key's to array objects

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!

like image 843
LeCoda Avatar asked Jun 30 '26 06:06

LeCoda


1 Answers

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);
like image 157
Siva K V Avatar answered Jul 01 '26 19:07

Siva K V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!