使用下划线更改对象数组的值

时间:2015-12-09 23:39:11

标签: javascript underscore.js

我有以下对象:

Object x - is an array of objects which look like below:
     name: "test1"
     value: Array[3]
        0: "string1"
        1: "string2"
        2: "string3"
     name: "test2"
     value: Array[3]
        0: "string1"
        1: "string2"
        2: "string3"

依旧......

我想迭代x中的对象并通过在每个对象中附加字符串来修改值,因此结果如下:

    name: "test1"
    value: Array[3]
        0: "string1appended"
        1: "string2appended"
        2: "string3appended"

我尝试了以下但是看起来效率低下:

.each(x, function(x1) {.each(x1, function(x2) {
    _.map(x2, function(i) {
      return i + "appended";
    })
  })
});

3 个答案:

答案 0 :(得分:1)

我的版本不需要map

_.each(arr, function (el) {
  _.each(el.value, function (v, i) {
    el.value[i] += 'appended';
  });
});

答案 1 :(得分:0)

您可以尝试:

 _.each(x,function(obj){
   obj.value = obj.value.join('appended ').concat('appended').split(' ');
 });

var x = [{
   name: "test1",
   value: ["string1", "string2", "string3"]
 }, {
   name: "test2",
   value: ["string1", "string2", "string3"]
 }];
 _.each(x, function(obj) {
   obj.value = obj.value.join('appended ').concat('appended').split(' ');
 });
 console.log(x);

答案 2 :(得分:-1)

所以解决方案是:

_.each(x, function(x1){x1.value = _.map(x1.value, function(x2) { return x2+'appended'})})