Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  153] [ 4]  / answers: 1 / hits: 29903  / 10 Years ago, sun, november 2, 2014, 12:00:00

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


More From » javascript

 Answers
13

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")

[#68940] Thursday, October 30, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rickjordond

Total Points: 100
Total Questions: 105
Total Answers: 90

Location: Sweden
Member since Mon, May 8, 2023
1 Year ago
rickjordond questions
;