给数组对象分配键值

3
我正在尝试解决这个问题。基本上,我有一组键的数组和对象中值的数组,我想让这些值成为键。
以下是目前为止我最好的尝试-通常使用Python,所以这对我来说有点困惑。
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);

我需要的输出应该是这样的:
results = [{3:1,4:2,5:3,6:4}, {..},..]

能否给一些获得正确输出的指针。

注意。这是为Google AppScript编写的!因此无法使用某些JavaScript函数(例如MAP可能不起作用,reduce不确定)。

干杯!

3个回答

2

在选择中使用mapObject.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);


1
创建一个单独的函数,将键和值作为参数,并使用 reduce() 将其转换为对象。然后对 selections 应用 map(),并使用该函数为每个子数组创建一个对象。

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)


0

为每个数字数组从头创建一个new对象:

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)));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接