简体   繁体   English

通过“添加”数组来增加Javascript对象的值

[英]Increment Javascript object values by “adding” an array

I have this javascript object: 我有这个javascript对象:

{"Vanilla": 36, "Chocolate": 50, "Stracciatella": 24, "Coffee": 18}

to which I would like to "add" this array: 我想向其“添加”此数组:

["Vanilla", "Amarena", "Chocolate", "Pistachio"]

The result I want is this: 我想要的结果是这样的:

{
    "Vanilla": 37,
    "Chocolate": 51,
    "Stracciatella": 24,
    "Coffee": 18,
    "Amarena": 1,
    "Pistachio": 1
}

This is what I have tried: 这是我尝试过的:

var me = ["Vanilla", "Amarena", "Chocolate", "Pistachio"]
var all = {
    "Vanilla": 36,
    "Chocolate": 50,
    "Stracciatella": 24,
    "Coffee": 18
}
var keys = Object.keys(all);
for (var i = 0; i < me.length; i++) {
    if (me[i] in keys) {
        console.log("keys:" + keys + " - " + me[i] + " in keys");
    } else {
        console.log("keys:" + keys + " - " + me[i] + " not in keys");

    };
}

console.log(keys);

The following code allows you to increment the values within your object stock based on the keys in your array stockUpdate : 以下代码允许您基于数组stockUpdate的键来增加对象stock的值:

var stockUpdate = ["Vanilla", "Amarena", "Chocolate", "Pistachio"];
var stock = {
    "Vanilla": 36,
    "Chocolate": 50,
    "Stracciatella": 24,
    "Coffee": 18
};

for (var i=0; i < stockUpdate.length; i++) {
    var stockType = stockUpdate[i];
    if (stock[stockType] === undefined) {
        stock[stockType] = 0;
    }
    stock[stockType]++;
}

This works 这有效

the first part of the code in your fiddle 代码在你的小提琴第一部分

var me = ["Vanilla", "Amarena", "Chocolate", "Pistachio"]
var all = {
    "Vanilla": 36,
    "Chocolate": 50,
    "Stracciatella": 24,
    "Coffee": 18
}

Now the answer: 现在的答案:

me.forEach(function(key) { // forEach iterates through an array 
    all[key] = (all[key] || 0) + 1; // create new item if it doesn't exist
});

The forEach() method executes a provided function once per array element. forEach()方法每个数组元素执行一次提供的函数。

For a more detailed description of .forEach see MDN documentation where the above description came from 有关.forEach的更详细说明,请参见上面的说明来自的MDN文档

as this question was tagged jQuery , lets add some jQuery code, just for laughs 正如这个问题被标记为jQuery ,让我们添加一些jQuery代码,只是为了笑

$.each(me, function(unusedIndex, key) {
    all[key] = (all[key] || 0) + 1;exist
});

jQuery.each() A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. jQuery.each()一个通用的迭代器函数,可用于对对象和数组进行无缝迭代。 Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. 具有长度属性的数组和类似数组的对象(例如函数的arguments对象)通过从0到length-1的数字索引进行迭代。 Other objects are iterated via their named properties. 其他对象通过其命名属性进行迭代。 - source http://api.jquery.com/jquery.each/ -来源http://api.jquery.com/jquery.each/

Here's me playing with myself - http://jsfiddle.net/7ephp3f4/1/ 这是我和我自己一起玩-http: //jsfiddle.net/7ephp3f4/1/

you are almost there, 你快到了

var me = ["Vanilla", "Amarena", "Chocolate", "Pistachio"]
var all = {
    "Vanilla": 36,
    "Chocolate": 50,
    "Stracciatella": 24,
    "Coffee": 18
}
var keys = Object.keys(all);
for (var i = 0; i < me.length; i++) {
    if (keys.indexOf(me[i]) >= 0) {
        console.log("keys:" + keys + " - " + me[i] + " in keys \n");
        all[me[i]]++;
    } else {
        console.log("keys:" + keys + " - " + me[i] + " not in keys \n");
        all[me[i]] = 1;
    };
}

console.log(all);

you can also use reduce to "merge" the newItems into items 您还可以使用reduce将newItems “合并”到items

var items = {"Vanilla": 36, "Chocolate": 50, "Stracciatella": 24, "Coffee": 18}
var newItems = ["Vanilla", "Amarena", "Chocolate", "Pistachio"];

var result = newItems.reduce(function(pre, curr) {
        // use double == to check when the item is either undefined or null
        pre[curr] = (pre[curr] == null? 0 : pre[curr]) + 1;
        return pre;
// pass items as the initial data to reduce
}, items);

console.log(result);

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value. reduce()方法对一个累加器应用一个函数,该数组的每个值(从左到右)将其减小为单个值。

in this case, I reduce the newItems list, from left to right, calcuate the count in the items object, and return the calculated items. 在这种情况下,我newItems缩小了newItems列表,计算了items对象中的计数,并返回了计算出的项目。

It is a good moment to use http://underscorejs.org : 现在是使用http://underscorejs.org的好时机:

var me = ["Vanilla", "Amarena", "Chocolate", "Pistachio"];

var all = {
  "Vanilla": 36,
  "Chocolate": 50,
  "Stracciatella": 24,
  "Coffee": 18
};

_.each(me, function(name) {
  if (_.has(all, name)) {
    all[name]++;
  } else {
    all[name] = 1;
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM