添加或删除元素到数组

时间:2015-11-10 14:55:23

标签: javascript arrays

我有一个现有的对象数组:

existingArray = [
   {object1: 'object1'},
   {object2: 'object2'}
   {object3: 'object3'},
]

我收到一个新的:

newArray = [
   {object2: 'object2'},
   {object3: 'object3'},
   {object4: 'object4'}
]

我只想修改现有的一个以获得新的结果(push + splice)

这就是我现在所拥有的(有更好的方法吗?)

 for (var i = 0; i < newArray.length; i++) {
    // loop first to push new elements
    var responseToTxt = JSON.stringify(newArray[i]);

    var newStatement = false;
    for(var j = 0; j < existingArray.length; j++){
        var statementToTxt = JSON.stringify(existingArray[j]);

        if(statementToTxt === responseToTxt && !newStatement){
            newStatement = true;
        }           
    }

    if(!newStatement){
        statements.push(response[i]);
    }  
}

var statementsToSplice = [];

for (var i = 0; i < existingArray.length; i++) {
    // then loop a second time to split elements not anymore on the new array
    var statementToTxt = JSON.stringify(existingArray[i]);        
    var elementPresent = false;
    var element = false;

    for(var j = 0; j < newArray.length; j++){       
        var responseToTxt = JSON.stringify(newArray[j]);
        if(responseToTxt === statementToTxt && !elementPresent){
            elementPresent = true;
        } else {
            element = i;   
        }
    }

    if(!elementPresent){   
        statementsToSplice.push(element);
    }  
}

然后我需要在数组中多次拆分:

existingArray = statementsToSplice.reduceRight(function (arr, it) {
        arr.splice(it, 1);
        return arr;
    }, existingArray.sort(function (a, b) { return b - a }));

以下是示例:

https://jsfiddle.net/docmz22b/

因此,最终输出应该始终是新数组,但只能通过推送或拼接旧数组。

在这种情况下,最终的输出将是

existingArray = [
       {object2: 'object2'},
       {object3: 'object3'}
       {object4: 'object4'},
    ]

新数组可能包含当前在existingArray

中的多个新元素和/或已删除元素

3 个答案:

答案 0 :(得分:0)

使用shift()push()

existingArray.shift(); //Removes the first element of the array
existingArray.push({'object4' : 'object4'});

Fiddle

答案 1 :(得分:0)

也许这有帮助。它具有Array.prototype.forEachArray.prototype.some

  1. 拼接不需要的物品
  2. 查看是否存在具有相同属性的对象

    • 如果是,则分配新对象
    • 其他推送对象
  3. &#13;
    &#13;
    var existingArray = [
            { object1: 'object1' },
            { object2: 'object2' },
            { object3: 'object3' },
        ],
        newArray = [
            { object2: 'object22' },
            { object3: 'object33' },
            { object4: 'object44' }
        ];
    
    function update(base, change) {
        var changeKeys = change.map(function (a) { return Object.keys(a)[0]; }),
            i = 0;
        while (i < base.length) {
            if (!~changeKeys.indexOf(Object.keys(base[i])[0])) {
                base.splice(i, 1);
                continue;
            }
            i++;
        }
        change.forEach(function (a) {
            var aKey = Object.keys(a)[0];
            !base.some(function (b, i, bb) {
                if (aKey === Object.keys(b)[0]) {
                    bb[i] = a; // if that does not work, use bb.splice(i, 1, a);
                    return true;
                }
            }) && base.push(a);
        });
    }
    
    update(existingArray, newArray);
    document.write('<pre>' + JSON.stringify(existingArray, 0, 4) + '</pre>');
    &#13;
    &#13;
    &#13;

答案 2 :(得分:0)

我几乎100%确定有更好的方法可以做到这一点,但至少可行,请随意评论任何建议/优化。

existingArray = [
   {object1: 'object1'},
   {object2: 'object2'},
   {object3: 'object3'}
];

newArray = [
   {object2: 'object2'},
   {object3: 'object3'},
   {object4: 'object4'}
];

// Loop all the old values, if is not in the new array, remove it
existingArray.forEach(function(item) {
  if(!inArray(item, newArray)) {
    var idx = indexOfObjectInArray(item, existingArray);
    existingArray.splice(idx, 1);
  }
});

// Loop all the new values, if  is not in the new array, push it
newArray.forEach(function(item) {
  if (!inArray(item, existingArray)) {
    existingArray.push(item);
  }
});

// Auxiliar functions
function inArray(initialValue, array) {
  testValue = JSON.stringify(initialValue);

  return array.some(function(item) {
    return testValue == JSON.stringify(item);
  });
}

function indexOfObjectInArray(initialValue, array) {
  var result = -1;
  testValue = JSON.stringify(initialValue);

  array.forEach(function(item, idx) {
    if (testValue == JSON.stringify(item)) {
      result = idx;
    };
  });

  return result;
}