Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update/add element of the array in JavaScript?

Tags:

javascript

How can I update/add element in the array?

var persons = {
    data: []
};

var bob = {name: 'Bob', age: 15};
var fill = {name: 'Fill', age: 20};
var mark = {name: 'Mark', age: 19};
var john = {name: 'John', age: 4};

persons['data'].push(bob);
persons['data'].push(fill);
persons['data'].push(mark);
persons['data'].push(john);

var updatedJohn = {name: 'John', age: 100};

if (!persons['data'][updatedJohn.name]){
    persons['data'].push(updatedJohn);
} else {
    persons['data'][updatedJohn.name] = updatedJohn; // this line doesn't work
}

I can't figure out how to update an element of the array if element John already exist.

UPDATE

jsFiddle example

like image 308
Alex Avatar asked Nov 02 '14 14:11

Alex


People also ask

How do you update an element in an array?

To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values.

How do you add an element to an array in Javascript?

When you want to add an element to the end of your array, use push() . If you need to add an element to the beginning of your array, use unshift() . If you want to add an element to a particular location of your array, use splice() .

How do you add an element to an array in array?

First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.

Can we modify array in Javascript?

push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements.


1 Answers

You will need a query function like the following to help you find indices according to a property in your database: (JSFiddle)

function findIndexByProperty(data, key, value) {
    for (var i = 0; i < data.length; i++) {
        if (data[i][key] == value) {
            return i;
        }
    }
    return -1;
}

var johnIndex = findIndexByProperty(persons.data, 'name', 'John');
if (johnIndex > -1) {
    persons.data[johnIndex] = updatedJohn;
} else {
    persons.data.push(updatedJohn);
}

Note that this only returns the first record with name John. You will need to decide what you want it to do in the case of multiple such records - update all of them? This kind of problem is why databases usually have unique keys to identify records.

If using Underscore or lodash you already have a _.findIndex() function that can be used instead:

var johnIndex = _.findIndex(persons.data, { name: 'John' }); 

2021 update: Using modern JavaScript you can replace the function with

const johnIndex = persons.data.findIndex(p => p.name === "John")
like image 59
Stuart Avatar answered Oct 16 '22 06:10

Stuart