【发布时间】:2018-01-25 23:23:05
【问题描述】:
我有一个像这样的 js 对象:
[{"product":7001,"quantity":1},{"product":3002,"quantity":1},{"product":4002,"quantity":4}]
我需要能够逐步重命名键,例如:
[{"product":7001,"quantity":1},{"product1":3002,"quantity1":1},{"product2":4002,"quantity2":4}]
我一直在努力为键名添加增量,但这不适用于我正在使用的对象类型。
任何建议将不胜感激。泰。
/*
this doesn't work
var a = [
{product : "3002", quantity: 1},
{product : "4001", quantity : 3}
];
*/
// this updates the key, but not in the way I need it to.
var a = {product : "3002", quantity: 1}
var n = 0;
function increment(string)
{
n++
return string + n;
}
var b = {};
var map = {
name : "name"
};
var keymap = {};
_.each(a, function(value, key) {
var oldkey = key;
key = increment(key);
keymap[oldkey] = key;
});
_.each(a, function(value, key) {
key = keymap[key] || key;
b[key] = value;
});
console.log('increment keys: ' + JSON.stringify(b));
【问题讨论】:
标签: javascript arrays dictionary underscore.js increment