Javascript Updating Values of Objects Inside List

How to update values of every object in an array of objects in Javascript?

Just take the index of the object being iterated over, and look it up in the newData array?

const data = [
{ id: 1, car: "Toyota 2020", owner: "BM" },
{ id: 2, car: "Nissan", owner: "DK" },
{ id: 3, car: "Mazda", owner: "JA" },
{ id: 4, car: "Ford", owner: "DS" }
];
const newData = ["Audi", "Bentley", "BMW", "Buick"];

const newCars = data.map((obj, i) => ({ ...obj, car: newData[i] }));
console.log(newCars);

Javascript: update nested object values from array of update objects

You can use a redursive approach here, we'll create a function updateNestedObj() to apply the updates, applying to each object and any of its child objects:

const objToUpdate = { children : [ { children : [ { children : [ { id : "F100517B-D00F", level : 4, note : "update me", parentId : "23A2A0DB-CCE3", title : "change me" } ], id : "23A2A0DB-CCE3", level : 3, note : "me too", parentId : "a0H4H00000Roi", title : "..and me" } ], id : "a0H4H00000Roi", level : 2, note : "none", parentId : "0064H00000ysL", title : "pending" }, { "children" : [ { id : "6A45E2EC-7825", level : 3, note : "|", parentId : "a0H4H00000Roi", title : "" } ], id : "a0H4H00000Roi", level : 2, note : "", parentId : "0064H00000ysL", title : "Change me" } ], id : "0064H00000ysL", level : 1, note : "hello", title : "Test Co" } 

const updateArr = [{ content: "New Co", id: "0064H00000ysL", note: "Here's your update" }, { content: "91%", id: "a0H4H00000Roi", note: "New note here" }];

function updateNestedObj(obj, updates) {
const updateToApply = updates.find(upd => upd.id === obj.id);
if (updateToApply) {
obj.title = updateToApply.content;
obj.note = updateToApply.note;
}
// Apply updates to any child objects
for(let k in obj) {
if (typeof(obj[k]) === 'object') {
updateNestedObj(obj[k], updates);
}
}
}

updateNestedObj(objToUpdate, updateArr);

console.log(objToUpdate)
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to update a value based on previous value in an array of objects?

Instead of having a step-wise transformation of your data, you can simply do all the operations you want in one go, using Array.prototype.reduce. The way we are going to use Array.prototype.reduce here is going to be almost similar to how you use Array.prototype.map (we are pushing the objects as-is into a new array, so there is no transformation of data), but the advantage is that we have access to the current index in the third argument, which allows us to access values of the previous item in the accumulator.

Array.prototype.map wouldn't work in this case because in each iteration it will not have access to the updated start in the previous item, unless you have a hack-ish way of storing it outside of the function.

With your logic, where you want start to be the duration + end of the previous item, we can use this logic:

curCopy.start = idx === 0 ? 1 : (acc[idx - 1].duration + acc[idx - 1].end);

...which basically says:

  1. If we are on the first item, just start with the seed value of 1 for start
  2. If not, then we access the previous entry (current index minus one) of the accumulator, and access its duration and end properties. Sum them up and use them for start

Use this logic in a new memoized array of objects returned:

const updatedRowData = React.useMemo(() => {
const updated = rowData.reduce((acc, cur, idx) => {
const curCopy = {...cur};
const previous = acc[idx - 1];
curCopy.start = idx === 0 ? 1 : (previous.duration + previous.end);
curCopy.end = curCopy.start + curCopy.stop;
acc.push(curCopy);
return acc;
}, []);

return updated;
}, [rowData]);

And then in your template, simply use rowData={updatedRowData}.
It should generate the results that you expected:

Expected table results

I have forked your sandbox to create a proof-of-concept example:

Edit ag-grid (forked)

Updating item in array of objects in Vue.js: is it better to replace the array or change one value

Vue has a different way of tracking when it comes to update the UI

Vue uses getters/setters on the data object for mutation tracking. When you execute this.table = [{}, {}, {}, ...];, It will go through the setter of table. In the setter, there's a function to notify the watcher and add this data changes to a queue.

Limitation/Behaviour while updating the Arrays :

Vue cannot detect the following changes to an array :

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  2. When you modify the length of the array, e.g. vm.items.length = newLength

Demo as per above two statements :

const app = new Vue({
el: '#app',
data() {
return {
table: [{
id:1,
column_1:'data1',
column_2:'data',
column_3:{'1':'data','2':'data','3':'data'}
}, {
id:2,
column_1:'data2',
column_2:'data',
column_3:{'1':'data','2':'data','3':'data'}
}]
}
},
mounted() {
// We are updating the array item and It's not reactive (You can see it's not updating UI)
this.table[1] = {
id: 3,
column_1: 'data3',
column_2:'data',
column_3:{'1':'data','2':'data','3':'data'}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="item in table" :key="item.id">
{{ item.column_1 }}
</li>
</ul>
</div>

Update specific values in a object with a conditional

Object.entries breaks down an object into an array of key, value pairs. Then you can easily map that array to another array with the recurrentSunday property set how you want. Then recreate your object using Object.fromEntries. You will need a browser that supports entries and fromEntries, which were introduced in ECMAScript 2019.

const testObj = () => {
let objAttrDay = {
"1": {
"sunday": false,
"recurrentSunday": false
},
"2": {
"sunday": true,
"recurrentSunday": false
},
"3": {
"sunday": true,
"recurrentSunday": false
}
};
let contSunday = 3;
if (contSunday >= 3) {
let entries = Object.entries(objAttrDay);
entries = entries.map(([key, value]) => {
return [key, {
...value,
recurrentSunday: value.sunday
}];
});
objAttrDay = Object.fromEntries(entries);
}
console.log(objAttrDay);
}
testObj();


Related Topics



Leave a reply



Submit