I have two separate sets of objects, storedArray
is saved in my file system and inputArray
is created from user input to update storedArray
. Each array has a minimum length of 1 with no maximum limit. They may not necessarily be the same length. My goal is to iterate over each array and:
- If the name from
inputArray
matches the name instoredArray
and the age is the same, then do nothing instoredArray
but keep that object instoredArray
(e.g., John). - If the name from
inputArray
matches the name instoredArray
but the age is different, update only the age value in the existing object instoredArray
(e.g., Jane). - If there is a new object in
inputArray
with a different name that doesn't match any names instoredArray
, push the new object tostoredArray
(e.g., Morris). - Must remove other objects in
storedArray
that do not match those ininputArray
(e.g., Joanna, Jim).
Transform this:
const storedArray = [
{"name": "John", "age": 25, "courses": 5},
{"name": "Jane", "age": 21, "courses": 3},
{"name": "Joanna", "age": 19, "courses": 2},
{"name": "Jim", "age": 20, "courses": 4},
];
to this:
const storedArray = [
{"name": "John", "age": 25, "courses": 5},
{"name": "Jane", "age": 23, "courses": 3},
{"name": "Morris", "age": 18, "courses": 0}
];
I attempted to achieve this using a for of
loop but encountered 22 results, some of which were missing. Additionally, I tried pushing it into a new array. While similar posts exist on SO, their end goals differ from mine. Nonetheless, I tested their code without success.
This is what I have tried:
const storedArray = [
{"name": "John", "age": 25, "courses": 5},
{"name": "Jane", "age": 21, "courses": 3},
{"name": "Joanna", "age": 19, "courses": 2},
{"name": "Jim", "age": 20, "courses": 4}
];
const inputArray = [
{"name": "Jane", "age": 23, "courses": 0},
{"name": "John", "age": 25, "courses": 0},
{"name": "Morris", "age": 18, "courses": 0}
];
let newArray = [];
for(let item of storedArray) {
for(let each of inputArray) {
if(item.name === each.name && item.age === each.age){
newArray.push(item);
}else if(item.name === each.name && item.age !== each.age) {
item.age = each.age;
newArray.push(item);
}else if(item.name !== each.name){
newArray.push(each);
newArray.push(item);
}
}
}
console.log(newArray);