下划线地图键名称w / increment

时间:2018-01-25 23:23:05

标签: javascript arrays dictionary underscore.js 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}]

我一直致力于为键名增加一些增量,但这对我正在使用的对象类型不起作用。

任何建议都将不胜感激。 TY。

/*
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));

3 个答案:

答案 0 :(得分:0)

我有一个更好的主意。为什么不向对象添加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); 




答案 1 :(得分:0)

看起来像一个不寻常的请求和不寻常的结构,但这里是一个产生预期结果的map / reduce



let firebasequery = info.child('todaysTotal')
var totalToday = 0

firebasequery.once('value', snap => {
  let theNumber = snap.val()
  totalToday = theNumber
})

console.log(totalToday)




答案 2 :(得分:0)

使用_.map()迭代数组。由于下划线无法映射键,因此您可以_.invert()键和值,使用_.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>
&#13;
&#13;
&#13;

使用Array.map()computed property names在ES6中执行此操作要容易得多:

&#13;
&#13;
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)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;