0

I have the array as follows, I want to first check if the record in array already exists, and then push the similar record.

    arr1 = [{
        'Name': 'Ken',
         'Id' : 123,
         'Units' : 100
    }, {
        'Name': 'Kris',
        'Id': '223',
        'Units' : 100 
    }, {
        'Name': 'Ben',
        'Id': '229',
        'Units' : 100
    },
     {
        'Name': 'Alex',
        'Id': '222',
        'Units' : 100
    }]

Now suppose I want to add a similar record

{
        'Name': 'Ken',
         'Id' : 123,
         'Units' : 50
}

Here only the value of Units have been changed and sometimes it may also remain same.

What I want is remove the initial similar record (check by Id) and push the new one.

So my final array should be like

arr1 = [{
        'Name': 'Ken',
         'Id' : 123,
         'Units' : 100
    }, {
        'Name': 'Kris',
        'Id': '223',
        'Units' : 100 
    }, {
        'Name': 'Ben',
        'Id': '229',
        'Units' : 100
    },
     {
        'Name': 'Alex',
        'Id': '222',
        'Units' : 100
    }]
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
Techy
  • 41
  • 4

2 Answers2

1
var newRecord = {
    'Name': 'Ken',
    'Id': 123,
    'Units': 50
};

arr1 = arr.filter(function (el) {
    return el.Id != newRecord.Id;
});

arr1.push(newRecord);

Demo:

arr1 = [{
  'Name': 'Ken',
  'Id': 123,
  'Units': 100
}, {
  'Name': 'Kris',
  'Id': '223',
  'Units': 100
}, {
  'Name': 'Ben',
  'Id': '229',
  'Units': 100
}, {
  'Name': 'Alex',
  'Id': '222',
  'Units': 100
}]

var newRecord = {
  'Name': 'Ken',
  'Id': 123,
  'Units': 50
};

arr1 = arr1.filter(function(el) {
  return el.Id != newRecord.Id;
});

arr1.push(newRecord);

alert(JSON.stringify(arr1));
CoderPi
  • 12,985
  • 4
  • 34
  • 62
  • The OP said: What I want is remove the initial similar record (check by Id) and push the new one. – Ziki Nov 26 '15 at 08:46
0

filter out the old record based on the pertinent property and add the new one.

similarRecord = {
  id = 123
  ...
}

_arr1 = arr1.filter(function(obj){
  return obj.id != similarRecord.id
})

_arr1.push(similarRecord)
Neil
  • 1
  • 2