如何使用不同的键名循环对象,但是相同的位置

时间:2016-11-22 21:26:12

标签: javascript

我有一个对象,其中有不同的奶牛数量变量(以奶牛为例),并且该对象不遵循任何特定的模式。

var cow = [
            //{variable: amount, name: "name"},
            {redcow: 0, name: "Redcow"},
            {bluecow: 0, name: "Bluecow"},
            {yellowcow: 0, name: "Yellowcow"}, 
            {purplecow: 0, name: "Purplecow"},
            {greencow: 0, name:"Greencow"}]

现在我想制作一个循环来循环不同类型的奶牛并检查每种奶牛的数量,然后输出名称数量

3 个答案:

答案 0 :(得分:1)

您可以迭代密钥并仅使用不等于名称的密钥。



var cow = [{ redcow: 1, name: "Redcow" }, { bluecow: 2, name: "Bluecow" }, { yellowcow: 3, name: "Yellowcow" }, { purplecow: 4, name: "Purplecow" }, { greencow: 5, name: "Greencow" }];

cow.forEach(function (o) {
    var countKey;
    Object.keys(o).some(function (k) {
        if (k !== 'name') {
            countKey = k;
            return true;
        }
    });
    console.log(o.name, o[countKey]);
});




答案 1 :(得分:0)

很抱歉告诉您,但您的数据结构有点破碎。 为什么不使用

{amount: 0, name: "Redcow"}

而不是

{redcow: 0, name: "Redcow"}

然后显示名称和金额将是微不足道的。

如果您真的想使用此结构,则amount键是小写名称:



var cows = [
            //{variable: amount, name: "name"},
            {redcow: 3, name: "Redcow"},
            {bluecow: 5, name: "Bluecow"},
            {yellowcow: 4, name: "Yellowcow"}, 
            {purplecow: 2, name: "Purplecow"},
            {greencow: 1, name:"Greencow"},
            {whatevercow: 99, name:"Orangecow"}
];

for (i = 0; i < cows.length; i++) {
    var cow = cows[i];
    var name = cow.name;
    var count = cow[name.toLowerCase()];
    console.log(name, count);
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
var cow = [
    {
        redcow: 0,
        name: "Redcow"
    }, {
        bluecow: 0,
        name: "Bluecow"
    }, {
        yellowcow: 0,
        name: "Yellowcow"
    }, {
        purplecow: 0,
        name: "Purplecow"
    }, {
        greencow: 0,
        name: "Greencow"
    }
];

cow.forEach(function(item) {
    var count = {
        name: item.name,
        amount: item[Object.keys(item)[0]]
    }
    console.log(count);
});
&#13;
&#13;
&#13;