带增量的下划线映射键名称

underscore map key name w/ increment

我有一个像这样的 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));

我有一个更好的主意。为什么不向对象添加 ID 密钥而不是更改密钥名称。以下代码循环遍历数组并创建一个新数组。新数组中的对象现在有一个对应于产品索引的 id 键。

    let products = [{"product":7001,"quantity":1},{"product":3002,"quantity":1},{"product":4002,"quantity":4}];

    products = products.map((item, index) => Object.assign(item, { id: index + 1 }));

    console.log(products); 

似乎是一个不寻常的请求和不寻常的结构,但这里的 map/reduce 产生了预期的结果

var data = [{"product":7001,"quantity":1},{"product":3002,"quantity":1},{"product":4002,"quantity":4}],

res = data.map((o,i)=>Object.keys(o).reduce((o2, key)=> i ? (o2[key+i] = o[key],o2):o,{}))

console.log(res)

_.map(). Because underscore lacks the ability to map keys, you can _.invert() the keys and the values, update the keys (the current values) with _.mapObject()迭代数组,然后再次_.invert()

var data = [{"product":7001,"quantity":1},{"product":3002,"quantity":1},{"product":4002,"quantity":4}]

var result = _.map(data, function(o, i) {
  return _.chain(o)
    .invert()
    .mapObject(function(v) { return v + (i || '') })
    .invert()
    .value()
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

在 ES6 中使用 Array.map() and computed property names 更容易做到这一点:

var data = [{"product":7001,"quantity":1},{"product":3002,"quantity":1},{"product":4002,"quantity":4}]

var result = data.map(({ product, quantity }, i) => ({
  [`product${i || ''}`]: product,
  [`quantity${i || ''}`]: quantity
}));

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>