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 OverflowYou 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);
You could use Array.reduce to copy the array with the new devices disabled:
const devices = [ /* ... */ ];
const newDevices = devices.reduce((ds, d) => {
let newD = d;
if (d.deviceID === 'eI2K-6iUvVw:APA') {
newD = Object.assign({}, d, { enabled: false });
}
return ds.concat(newD);
}, []);
Replace object value with other object's value of the same key with JavaScript - Stack Overflow
javascript - How can I find and update values in an array of objects? - Stack Overflow
jquery - Find and Replace value in Javascript object - Stack Overflow
javascript - How to find and replace value in JSON? - Stack Overflow
It could do the trick !
var item = {};
var results={};
item.id = '50'
item.area = 'Mexico'
item.gender = null
item.birthdate = null
results.id = '50'
results.area = null
results.gender = 'Male'
results.birthdate = null
Object.keys(item).forEach(function(key) {
if (item[key] == null || item[key] == 0) {
item[key] = results[key];
}
})
document.getElementById('dbg').innerHTML ='<pre>' + JSON.stringify(item , null , ' ') + '</pre>';
console.dir(item);
<div id='dbg'></div>
You can elegantly use lodash:
var results = {};
var item = {};
item.id = '50';
item.area = 'Mexico';
item.gender = null;
item.birthdate = null;
results.id = '50';
results.area = null;
results.gender = 'Male';
results.birthdate = null;
_.merge(results, _.pick(item, _.identity));
alert(JSON.stringify(results));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
Note that the requested value is now in results (and not in item). If you still need it item, clone the values into a new variable and use it.
ยป npm install find-and-replace-anything
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;
}
});
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.
for(var i=0; i<result.length; i++)
if(result[i].length >= 2)
result[i][1] = result[i][1].replace(/^Total$/, "xxxx").replace(/^Data$/, "DDDD");
iteration, iteration, iteration
for (key in obj) {
for (var i=0; i<obj[key].length; i++) {
for (var j=0; j<obj[key][i].length; j++) {
if (obj[key][i][j] == 'Total') obj[key][i][j] = 'XXXX';
if (obj[key][i][j] == 'Data') obj[key][i][j] = 'DDDD';
}
}
}
FIDDLE
The javascript object should be iterated and then each value of name can be checked and replaced. There are checks such as hasOwnProperty() that can be used to make sure you are not iterating objects that are missing "items" or "name" for better error handling.
var data = {
"responses": {
"firstKey": {
"items": {
"name": "test name one"
}
},
"anotherKey": {
"items": {
"name": "test name two"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
};
Given the JSON above you can use a simple for statement to iterate and then check each name for some value and replace.
for(var key in data.responses){
if ((data.responses[key].items.name).match(/test name/)){
data.responses[key].items.name = "N/A";
}
}
To check your replacements you can log data to the console.
console.log(JSON.stringify(data));
It can also be done during parsing :
var json = `{
"responses": {
"firstKey": {
"items": {
"name": "test name one"
}
},
"anotherKey": {
"items": {
"name": "test name two"
}
},
"oneMoreKey": {
"items": {
"name": "John"
}
}
}
}`
var obj = JSON.parse(json, (k, v) => k == 'name' && /^test name/.test(v) ? 'N/A' : v)
console.log( obj )
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Hello
I would like to change the the value of name by nationality in the object array bellow
How to to it?
let newlist = list.map(e => ({...e, name: e.nationality}) )
-
eis for "element", where the.mapmethod touches each element in a source array, and then returns a new array. -
newlistwill have your modified array.listremains unchanged. -
e =>begins an "arrow function". I want to return an object, but objects require curly braces, just like a function body. Defining an object{}and wrapping it in()sentinels tells JS that "these curlies are not a function body" -
without a function body, the "arrow function" expects a statement which it will then return by default without specifically using
returnkeyword. -
...edoes a js "spread" on theevariable. It takes the entire contents ofeand puts them right there as part of the new object. It then replaces the contents of thenameproperty with data from the current element.
The long way:
let newlist = list.map(function (element) {
element.name = element.nationality
return element
})
If you don't want a new array, then .forEach, and add a new key with the value of the name, then delete name.
If you want a new array, then .map and you can for example create a new item object with the needed keys. This can be done in many ways.
Use Array.map and Array.find():
const allItems = [
{ 'id': 1, 'category_id': 1, 'text': 'old' },
{ 'id': 2, 'category_id': 1, 'text': 'old' }
];
const newItems = [
{ 'id': 1, 'category_id': 1, 'text': 'new', 'more_info': 'abcd' },
{ 'id': 2, 'category_id': 1, 'text': 'new', 'more_info': 'abcd' }
];
const result = allItems.map(x => {
const item = newItems.find(({ id }) => id === x.id);
return item ? item : x;
});
console.log(result);
This can even be shortened by using a logical or to return the original item when the call to find returns undefined:
const result = allItems.map(x => newItems.find(({ id }) => id === x.id) || x);
Regarding your code, you can't use indexOf since it only compares primitive values or references in the case of arrays and objects.
Just use map like so:
const allItems = [{
'id': 1,
'category_id': 1,
'text': 'old',
},
{
'id': 2,
'category_id': 1,
'text': 'old'
}
];
const newItems = [{
'id': 1,
'category_id': 1,
'text': 'new',
'more_info': 'abcd'
},
{
'id': 2,
'category_id': 1,
'text': 'new',
'more_info': 'abcd'
}
];
const replacedItems = allItems.map(e => {
if (newItems.some(({ id }) => id == e.id)) {
return newItems.find(({ id }) => id == e.id);
}
return e;
});
console.log(replacedItems);
Assuming your JSON array is stored in the variable data:
data.forEach(item => item.label = item.name)
This would be sufficient to duplicate the name property as the label property for each item in the array.
I have created a function replace() to deal with every object and nested objects, which will add property 'label' if 'name' property is found. Pls see if it's useful to you.
var arr = [
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID"
}
},
{
"itemType": "SelectionTitle",
"name": "test",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "testing"
}
}
]
// this method will take care of adding new property
function replace(obj, from, to) {
Object.entries(obj).forEach(([key, value]) => (
key == from && (obj[to] = obj[from])
, typeof value === "object" && replace(value, from, to)
))
}
arr.forEach(d => replace(d, 'name', 'label'))
// you can check this log for property 'label' whereever 'name' exists
console.log(arr)