Sandeep Thomas
Sandeep Thomas

Reputation: 4759

Pushing objects onto an array without repeating the same

I've an array like this

var myArray = [{A:[{10:'a'},{11:'b'},{12:'c'}]},{B:[{10:'d'},{11:'e'},{12:'f'}]}]

So if I push the follwing object to the array by

myArray.push({A:[{10:'k'},{11:'j'},{12:'m'}]});

This should removes the existing array element "A" since the new one also the main is A and it should replaced by the new element.

So the new object should be like this

var myArray=[{A:[{10:'k'},{11:'j'},{12:'m'}]},{B:[{10:'d'},{11:'e'},{12:'f'}]}]

That means when the push that first element A get replaced by new

EDIT

Also A, B are dynamic. There may be more get inserted like D, E with the same sub structure for them. Actually thats the reason I used array. Its actually happening in a table with multiple pages. So if same element comes again in another page, that should replace the previous one. Thats the purpose

Upvotes: 1

Views: 409

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386868

  1. find index
  2. if found replace the element with new data
  3. if not found push the new data to the end of the array

var myArray = [{ A: [{ 10: 'a' }, { 11: 'b' }, { 12: 'c' }] }, { B: [{ 10: 'd' }, { 11: 'e' }, { 12: 'f' }] }],
    newData = { A: [{ 10: 'k' }, { 11: 'j' }, { 12: 'm' }] };

function update(a, u) {
    var index;
    if (a.some(function (el, i) { return Object.keys(u)[0] in el ? (index = i, true) : false; })) {
        a[index] = u;
    } else {
        a.push(u);
    }
}
update(myArray, newData);
document.getElementById('out').innerHTML = JSON.stringify(myArray, null, 4);
<pre id="out"></pre>

Upvotes: 1

Mouser
Mouser

Reputation: 13304

Push on arrays will only add a new value. It's better to upgrade your entire array to an object. Now you can select the correct key and overwrite its value.

Change to :

var myArray = {A : [{10:'a'},{11:'b'},{12:'c'}],B : [{10:'d'},{11:'e'},{12:'f'}]};

Now when you do :

 myJSON['A'] = [{10:'k'},{11:'j'},{12:'m'}];

It will replace A with the new values.

Even when A doesn't exists it will be created by this construction.

You can even iterate over them by using Object.keys

var myArray = {A : [{10:'a'},{11:'b'},{12:'c'}],B : [{10:'d'},{11:'e'},{12:'f'}]};
var keys = Object.keys(myArray);

for (var i = 0; i < keys.length; i++)
{
  document.body.innerHTML += keys[i] + " : " + myArray[keys[i]].join(", ") + "<br />";  
}

Upvotes: 1

Vale
Vale

Reputation: 2032

Just use a javascript Object, they basically act like an HashMap and will replace an element if they have the same key:

var myJSON = {
    A: [{10:'a'},{11:'b'},{12:'c'}],
    B: [{10:'d'},{11:'e'},{12:'f'}]
};
// will change the existing 'A' object    
myJSON['A'] = [{10:'k'},{11:'j'},{12:'m'}];

// add a new element like this
myJSON['C'] = [{10: 't'}, {11: 'g'}, {12: 'm'}];

Upvotes: 3

Related Questions