I have two different arrays of objects, storedArray
is stored in my file system and inputArray
is made from user's input to update storedArray
. The minimum length of each of the array is 1 and there's no cap on the maximum number. Also they doesn't necessarily have to be of the same length. So what I want is to loop over each array and:
- if name from
inputArray
matches with thestoredArray
name and age is same, then do nothing in thestoredArray
but keep that object instoredArray
. (example John). - if name from
inputArray
matches with thestoredArray
name and age is not same, then update only age value in the old object instoredArray
. (example Jane). - if there is a new object inside
inputArray
with a different name that doesn't match with any instoredArray
name, then push the new object tostoredArray
. (example Morris). - Must remove other objects in
storedArray
which does not match withinputArray
. (example Joanna, Jim).
Update 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},
];
from this
const inputArray = [
{"name": "Jane", "age": 23, "courses": 0},
{"name": "John", "age": 25, "courses": 0},
{"name": "Morris", "age": 18, "courses": 0}
];
to this:
const storedArray = [
{"name": "John", "age": 25, "courses": 5},
{"name": "Jane", "age": 23, "courses": 3},
{"name": "Morris", "age": 18, "courses": 0}
];
I tried this with for of
loop but I get 22 results. And some of them are missing. Moreover, I tried it by pushing it into a new array. There are other posts here in SO with the same titles but the end goal doesn't match with my one. But still I tried their code but doesn't work.
Here's what I 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);
courses
property in storedArray. They have values which I can't change. If I replace it then the matched objects make all the courses value to 0.