简体   繁体   中英

Most efficient way to update an object property within an array of objects

I am wondering what is the most efficient way to update an object property that is stored in an array with 10k+ items.

For example if I have an array that holds objects like this {name:"", price:"")

I want to replace or more like update the price values if the array contains that element already.

Check if Array contains object with name = x, if so replace the price with the newest price.

I dont want to have duplicate elements in that array so its not getting to big, i figured I should update it if a property value already exists in it.

So far I have tried several ways like with using indexOf, splice, or just for loops. I am wondering what is the best way performance wise to deal with big arrays.

 let array = [ {name:"abc", price: 24}, {name:"cde", price: 25}, {name:"fgh", price: 22}, {name:"gfds", price: 21}, ] function addToArray(elem){ //check if array contains elem by checking for name property value if(array.filter(el => el.name === elem.name).length > 0){ //update the array element that has the name of the passed elem } }

You've said your starting point is an array, but the most efficient way to do this is with a Map , not an array, where the key is the name and the value is either the price or an object containing the price (depending on whether you need other information).

But if you're doing this with an array, there's nothing more efficient than just looping through it looking for a previous element with the given name . filter isn't the right tool for that (you don't need the array it creates). You'd either write your own loop:

let element;
for (let index = 0, length = array.length; index < length; ++index) {
    const thisElement = array[index];
    if (thisElement.name === name) {
        // Already have one
        element = thisElement;
        break;
    }
}
if (element) {
    element.price += price;
} else {
    array.push({name, price});
}

...or use find :

const element = array.find(e => e.name === name);
if (element) {
    element.price += price;
} else {
    array.push({name, price});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM