我有一个var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
之类的数组,我希望能够遍历该数组以从每个元素创建一个对象。
var zoo = {
Dog : {
color: brown,
age: 4
},
Cat : {
color: black,
age: 12
我找到了一些使用.keys和.values定义其他属性的解决方案,但我仍然坚持如何命名对象。感谢您的帮助!
答案 0 :(得分:2)
您可以使用 Array.reduce
实现解决方案。
reduce提供了一种优雅的方式来根据您的数组返回所需的输出。
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var zoo=arr.reduce((zooObj, animal)=>
{
zooObj[animal] = {
color: 'black', //You can add color based on some logic here
age: 4 //You can add age based on some logic here
}
return zooObj
}, {})
console.log(zoo) //*Output*: { "Dog": { "color": "black", "age": 4 }, "Cat": { "color": "black", "age": 4 }, "Horse": { "color": "black", "age": 4 }, "Pig": { "color": "black", "age": 4 }, "Cow": { "color": "black", "age": 4 } }
答案 1 :(得分:1)
您可以尝试以下操作:
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var colors = ["Red", "Blue", "Green", "Dark", "Yellow"];
var zoo={};
var i = 10;
var colorIndex = 0;
arr.forEach(v=>{
zoo[v]={};
zoo[v].age=i++;
zoo[v].color=colors[colorIndex++];
});
console.log(zoo);
答案 2 :(得分:0)
您可以通过这种方式简单地完成此操作:
var objArr = {};
arr.forEach((data, index) => {
objArr[data] = data; //here you can add what ever value you want to add to that key
})
答案 3 :(得分:0)
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var zoo = {};
for (var i of arr ){
zoo[i] = {};
zoo[i].age = 'age'; //fill the age
zoo[i].color= 'your favorite color'; //fill with your favorite color
}
console.log(zoo);
答案 4 :(得分:0)
这可以做到
var animal = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var color=["red","green","blue","orange","yellow"];
var age=[2,5,8,6,23];
var obj={};
animal.forEach((e)=>{
obj[e]={};
obj[e].age=age[animal.indexOf(e)];
obj[e].color=color[animal.indexOf(e)];
})
console.log(obj)
答案 5 :(得分:0)
您可以使用以下逻辑来做到这一点。 在这里定义颜色和年龄数组,并在内部循环中动态存储它。
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var colors = ["brown","blak","white","red","gray"];
var ages = ["4","12","5","10","15"];
arr2 = {}
for(var i=0;i<arr.length;i++){
arr2[arr[i]] = {};
arr2[arr[i]].color = colors[i]; //fill the age
arr2[arr[i]].age= ages[i];
}
console.log(arr2);