我有以下字符串数组和单独的布尔数组。
const strings = ['a','b','c'];
const bools = [true, false, false];
const obj = {};
我如何将这些数组推到obj,以便得到结果:
{a: true, b: true, c: false}
答案 0 :(得分:2)
假设您要获得此结果:
obj = {a:true, b:false, c:false}
这应该有效:
const strings = ['a', 'b', 'c'];
const bools = [true, false, false];
const obj = {};
for (let i = 0; i < strings.length; ++i) {
obj[strings[i]] = bools[i];
}
console.log(obj); // outputs {a:true, b:false, c:false}
答案 1 :(得分:1)
最有效的方式:
const strings = ['a','b','c'];
const bools = [true, false, false];
let obj = {};
for (let i = 0; i < strings.length; i++) {
obj[strings[i]] = bools[i]
}
console.log(obj)
答案 2 :(得分:0)
因此,由于要使用的结构是无效的javascript,因此您无法完全执行所需的操作,但是可以生成语义上相似的结构,该函数可实现以下结果:
{'a': true, 'b': true, 'c': true}
看起来像这样:
const zipTwoArraysToObject = (arr1, arr2) => arr1.reduce((memo, item1, index) => {
memo[item1] = arr2[index]
return memo
}, {})
产生以下内容的函数:
[{'a': true}, {'b': true}, {'c': true}]
看起来像这样:
const zipTwoArraysToArrayOfObjects = (arr1, arr2) => arr1.map((item1, index) => {
const tempStore = {}
tempStore[item1] = arr2[index]
return tempStore
})
两者均处于运行状态的代码段:
const zipTwoArraysToObject = (arr1, arr2) => arr1.reduce((memo, item1, index) => {
memo[item1] = arr2[index]
return memo
}, {})
const zipTwoArraysToArrayOfObjects = (arr1, arr2) => arr1.map((item1, index) => {
const tempStore = {}
tempStore[item1] = arr2[index]
return tempStore
})
const strings = ['a', 'b', 'c']
const bools = [true, true, true]
console.log('zipTwoArraysToObject', zipTwoArraysToObject(strings, bools))
console.log('zipTwoArraysToArrayOfObjects', zipTwoArraysToArrayOfObjects(strings, bools))
答案 3 :(得分:0)
要获得结果,请使用forEach和index遍历字符串数组,并使用索引使用bools数组将值分配给obj
const strings = ['a','b','c'];
const bools = [true, false, false];
const obj = {};
strings.forEach((v, i) => obj[v] = bools[i])
console.log(obj)
codepen-https://codepen.io/nagasai/pen/MBNvXE?editors=1010
const strings = ['a','b','c'];
const bools = [true, false, false];
const obj = {};
strings.forEach((v, i) => obj[v] = bools[i])
console.log(obj)
答案 4 :(得分:0)
在一行中使用reduce:
const strings = ['a','b','c'];
const bools = [true, false, false];
var obj = strings.reduce((x, y, z) => { x[y] = bools[z]; return x; }, {});
console.log(obj);