You can use Array#find.

let arr = [
  {
    "enabled": true,
    "deviceID": "eI2K-6iUvVw:APA",
  },
  {
    "enabled": true,
    "deviceID": "e_Fhn7sWzXE:APA",
  },
  {
    "enabled": true,
    "deviceID": "e65K-6RRvVw:APA",
  },
];

const id = 'eI2K-6iUvVw:APA';

arr.find(v => v.deviceID === id).enabled = false;

console.log(arr);

Answer from kind user on Stack Overflow
๐ŸŒ
GitHub
github.com โ€บ mesqueeb โ€บ find-and-replace-anything
GitHub - mesqueeb/find-and-replace-anything: Replace one val with another or all occurrences in an object recursively. A simple & small integration. ยท GitHub
findAndReplace(target, 1, 2, {onlyPlainObjects: true}) // this will replace 1 with 2 only in the plain object and returns: {prop: 2, class: {prop: 1}} Also be careful with circular references!
Starred by 21 users
Forked by 2 users
Languages ย  TypeScript 96.4% | JavaScript 3.6%
Discussions

Replace object value with other object's value of the same key with JavaScript - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I've got two objects, item and results. They've both got the same keys but possibly different values... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - How can I find and update values in an array of objects? - Stack Overflow
You can use findIndex to find the index in the array of the object and replace it as required: More on stackoverflow.com
๐ŸŒ stackoverflow.com
jquery - Find and Replace value in Javascript object - Stack Overflow
I have following javascript object. On this object I want to perform find and replace operation. I want to replace values only for second column. I want to replace 'total' with XXXX and 'data' with... More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 18, 2013
javascript - How to find and replace value in JSON? - Stack Overflow
The javascript object should be iterated and then each value of name can be checked and replaced. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
JsCraft
js-craft.io โ€บ home โ€บ javascript โ€“ find and replace an object in array
Javascript โ€“ find and replace an object in array
November 30, 2023 - const deepEqual = (x, y)=> { const ok = Object.keys, tx = typeof x, ty = typeof y; return x && y && tx === 'object' && tx === ty ? ( ok(x).length === ok(y).length && ok(x).every(key => deepEqual(x[key], y[key])) ) : (x === y); } const myArray = [ "value 1", {age: 2}, {name: "The dog", age: 2} ] const searchedObj = {name: "The dog", age: 2} const replacingObj = {name: "The cat", age: 3} const i = myArray.findIndex(x => deepEqual(x, searchedObj)) myArray[i] = replacingObj console.log(myArray)
๐ŸŒ
IQCode
iqcode.com โ€บ code โ€บ javascript โ€บ find-and-replace-value-in-array-of-objects-javascript
find and replace value in array of objects javascript Code Example
September 27, 2021 - let arr = [ { "enabled": true, "deviceID": "eI2K-6iUvVw:APA", }, { "enabled": true, "deviceID": "e_Fhn7sWzXE:APA", }, { "enabled": true, "deviceID": "e65K-6RRvVw:APA", }, ]; const id = 'eI2K-6iUvVw:APA'; arr.find(v => v.deviceID === id).enabled = false; console.log(arr); ... Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-replace-the-names-of-multiple-object-keys-with-the-values-provided-using-javascript
How to replace the names of multiple object keys with the values provided using JavaScript ? | GeeksforGeeks
January 12, 2022 - Note: This approach will preserve the position of the key and also the value. ... To get all property values from a JavaScript object without knowing the keys involves accessing the object's properties and extracting their values.Below are the approaches to get all property values of a JavaScript Object:Table of ContentUsing Object.values() MethodUsing Object.keys() methodApproac
๐ŸŒ
npm
npmjs.com โ€บ package โ€บ find-and-replace-anything
find-and-replace-anything - npm
February 19, 2025 - /** * @param {*} target Target can be anything * @param {*} find val to find * @param {*} replaceWith val to replace * @returns the target with replaced values */ function findAndReplaceRecursively (target, find, replaceWith) { if (!isObject(target)) { if (target === find) return replaceWith return target } return Object.keys(target) .reduce((carry, key) => { const val = target[key] carry[key] = findAndReplaceRecursively(val, find, replaceWith) return carry }, {}) } find-and-replace ยท find-replace ยท find-and-replace-if ยท javascript ยท
      ยป npm install find-and-replace-anything
    
Published ย  Feb 19, 2025
Version ย  4.0.3
Author ย  Luca Ban - Mesqueeb
Top answer
1 of 12
475

You can use findIndex to find the index in the array of the object and replace it as required:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;

This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:

items.forEach((element, index) => {
    if(element.id === item.id) {
        items[index] = item;
    }
});
2 of 12
107

My best approach is:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

items[items.findIndex(el => el.id === item.id)] = item;

Reference for findIndex

And in case you don't want to replace with new object, but instead to copy the fields of item, you can use Object.assign:

Object.assign(items[items.findIndex(el => el.id === item.id)], item)

as an alternative with .map():

Object.assign(items, items.map(el => el.id === item.id? item : el))

Functional approach:

Don't modify the array, use a new one, so you don't generate side effects

const updatedItems = items.map(el => el.id === item.id ? item : el)

Note

Properly used, references to objects are not lost, so you could even use the original object reference, instead of creating new ones.

const myArr = [{ id: 1 }, { id: 2 }, { id: 9 }];
const [a, b, c] = myArr;
// modify original reference will change object in the array
a.color = 'green';
console.log(myArr[0].color); // outputs 'green'

This issue usually happens when consuming lists from database and then mapping the list to generate HTML content which will modify the elements of the list, and then we need to update the list and send it back to database as a list.

Good news is, references are kept, so you could organize your code to get advantage of it, and think about a list as an Object with identities for free, which are integers from 0 to length -1. So every time you access any property of your Object, do it as list[i], and you don't lose reference, and original object is changed. Keep in mind that this is useful when your source of truth is only one (the Object created), and your app is always consistently consuming the same Object (not fetching several times from database and assigning it to list along the lifespan of the component).

Bad news is that the architecture is wrong, and you should receive an object by ids (dictionary) if this is what you need, something like

{ 
  1232: { id: 1232, ...},
  asdf234asf: { id: 'asdf234asf', ...},
  ...
}

This way, you don't search in arrays, which is resource consuming. You "just access by key in the object", which is instant and performant.

Find elsewhere
๐ŸŒ
GitHub
gist.github.com โ€บ flipace โ€บ bed6b89aed5cb0e19cde
Deep replace a value within an object or array (using lodash or underscore) ยท GitHub
FYI: You can do it with lodash like this: _.cloneDeepWith(object, value => value === prevVal ? newVal : undefined). @ypresto as I would do, if instead of passing fn(prevVal, newVal, object), I would always have to pass inside an array with 1 object or more, example fn([{prevVal: 'old value', newVal: 'new value' }], object)
๐ŸŒ
W3Resource
w3resource.com โ€บ javascript โ€บ object-property-method โ€บ string-replace.php
JavaScript replace() Method : String Object - w3resource
<![CDATA[ regex = /brown/gi; str1 = "The Quick Brown Fox Jumps Over The Lazy Dog"; document.write("Original string : "+str1+"<br />"); document.write("Searched string : brown"+"<br />"); document.write("New string : white "+"<br />"); newstr=str1.replace(regex, "white"); document.write(newstr) //]]> </script> </body> </html> ... JavaScript Core objects, methods, properties. Previous: JavaScript match() Method: String Object Next: JavaScript search() Method: String Object ยท Test your Programming skills with w3resource's quiz. ๏ปฟ ยท Follow us on Facebook and Twitter for latest update.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ javascript โ€บ replace object in array javascript
How to Replace Object in an Array in JavaScript | Delft Stack
February 2, 2024 - This article demonstrates how to replace an object in an array in JavaScript using the index and splice method with examples.
๐ŸŒ
xjavascript
xjavascript.com โ€บ blog โ€บ find-a-value-in-an-array-of-objects-in-javascript
How to Find and Replace an Object by 'name' Property in a JavaScript Array โ€” xjavascript.com
Use findIndex() to get the index of the object with name: "Phone". If the index is -1 (no match), do nothing. Otherwise, replace the object at that index with the new object.
Top answer
1 of 1
9

Next to the way you proposed yourself, here is a classic loop approach. As mentioned by someone in a comment, it's more stable because you don't risk screwing the object up and throwing an error when trying to parse it back. On the other hand, some questions arise (see bottom).

Be careful, though, as the needle will be used as a regular expression. You may want to consider adding some sort of quoting to it.

I hope I didn't overlook anything, so test it and play around with it. Here you can find a fiddle.

/**
  * Replaces all occurrences of needle (interpreted as a regular expression with replacement and returns the new object.
  * 
  * @param entity The object on which the replacements should be applied to
  * @param needle The search phrase (as a regular expression)
  * @param replacement Replacement value
  * @param affectsKeys[optional=true] Whether keys should be replaced
  * @param affectsValues[optional=true] Whether values should be replaced
  */
Object.replaceAll = function (entity, needle, replacement, affectsKeys, affectsValues) {
    affectsKeys = typeof affectsKeys === "undefined" ? true : affectsKeys;
    affectsValues = typeof affectsValues === "undefined" ? true : affectsValues;

    var newEntity = {},
        regExp = new RegExp( needle, 'g' );
    for( var property in entity ) {
        if( !entity.hasOwnProperty( property ) ) {
            continue;
        }

        var value = entity[property],
            newProperty = property;

        if( affectsKeys ) {
            newProperty = property.replace( regExp, replacement );
        }

        if( affectsValues ) {
            if( typeof value === "object" ) {
                value = Object.replaceAll( value, needle, replacement, affectsKeys, affectsValues );
            } else if( typeof value === "string" ) {
                value = value.replace( regExp, replacement );
            }
        }

        newEntity[newProperty] = value;
    }

    return newEntity;
};

The last two parameters are optional, so it's perfectly fine to just call it like this:

var replaced = Object.replaceAll( { fooman: "The dog is fooking" }, "foo", "bar" );

However, there are still edge cases where it's unclear what should happen. For example:

// do you expect it to stay undefined or change type and become "undebazed"?
console.log( Object.replaceAll( { x: undefined }, "fin", "baz" ) );

// null or "nalala"?
console.log( Object.replaceAll( { x: null }, "ull", "alala" ) );

Or

// true or false?
console.log( Object.replaceAll( { x: true }, "true", "false" ) );

// true or "foo"?
console.log( Object.replaceAll( { x: true }, "true", "foo" ) );

And the same for numbers

// 1337 or 1007?
console.log( Object.replaceAll( { x: 1337 }, "33", "00" ) );

// 1337 or "1foo7"
console.log( Object.replaceAll( { x: 1337 }, "33", "foo" ) );

None of these cases are currently handled in my method โ€“ only objects (for nesting) and strings will be touched.

๐ŸŒ
Itsourcecode
itsourcecode.com โ€บ home โ€บ how to find and replace object in an array javascript?
How to Find and Replace Object in an Array JavaScript?
September 6, 2023 - You can use methods like indexOf() or a loop to search for the object based on specific criteria. ... Once you have identified the object to replace, create a new object with the desired changes or values.
๐ŸŒ
W3Resource
w3resource.com โ€บ javascript-exercises โ€บ fundamental โ€บ javascript-fundamental-exercise-14.php
JavaScript fundamental (ES6 Syntax): Replace the names of multiple object keys with the values provided - w3resource
July 3, 2025 - //#Source https://bit.ly/2neWfJ2 // Define a function called `rename_keys` that renames keys of an object based on a provided mapping. const rename_keys = (keysMap, obj) => Object.keys(obj).reduce( (acc, key) => ({ ...acc, ...{ [keysMap[key] ...