[英]How to group array as a key to an object
I'm struggling to group array as a key to an object.我正在努力将数组分组为对象的键。
var a = ["fruit1", "fruit2", "fruit3"]
var b = ["apple", "banana", "Orange"];
var obj = {};
a.forEach((x) => {
b.forEach((y) => {
obj[x] = y;
})
})
console.log(obj)
OUTPUT:输出:
{fruit1:apple,fruit2:banana:fruit3:orange}
In the inner loop you rewrite all object values with the last element of b
.在内部循环中,您使用
b
的最后一个元素重写所有对象值。 Try this to utilize the index argument of .forEach()
:试试这个来利用
.forEach()
的 index 参数:
var a = ["fruit1", "fruit2", "fruit3"]; var b = ["apple", "banana", "Orange"]; var obj = {}; a.forEach((x, i) => { obj[x] = b[i]; }); console.log(obj)
You can use zipObj function from ramda library which convert your arrays to an object just like below:您可以使用ramda库中的zipObj函数,它将数组转换为对象,如下所示:
const a = ["fruit1", "fruit2", "fruit3"] const b = ["apple", "banana", "Orange"]; const obj = R.zipObj(a, b) //{"fruit1": "apple", "fruit2": "banana", "fruit3": "Orange"} console.log(obj)
You could build an array of entries and then an object from it.您可以构建一个条目数组,然后从中构建一个对象。
const keys = ["fruit1", "fruit2", "fruit3"], values = ["apple", "banana", "Orange"], result = Object.fromEntries(keys.map((key, i) => [key, values[i]])); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.