I have an array like this
const ex = [
{
name: 'John',
sender: "12345678",
receiver: {
name: "simi",
age: 20,
city: "New York"
},
time: 12:30 am
},
{
name: 'Jane',
sender: {
name: "simi",
age: 20,
city: "New York"
},
receiver: "12345678",
time: 1:00 pm
}
]
In this array, the sender property value in the first object is equal to the receiver property value in the second object. Is there a way I can check and produce only one occurence of this value, that is, just one object in which the value is present
asked Sep 5, 2020 at 19:43
Similoluwa Odeyemi
4099 silver badges19 bronze badges
-
what does this value mean object value or property value?EugenSunic– EugenSunic2020年09月05日 19:48:46 +00:00Commented Sep 5, 2020 at 19:48
-
property value.Similoluwa Odeyemi– Similoluwa Odeyemi2020年09月05日 19:55:23 +00:00Commented Sep 5, 2020 at 19:55
1 Answer 1
Try this:
const ex = [
{
name: 'John',
sender: "12345678",
receiver: {
name: "simi",
age: 20,
city: "New York"
},
time: "12:30 am"
},
{
name: 'Jane',
sender: {
name: "simi",
age: 20,
city: "New York"
},
receiver: "12345678",
time: "1:00 pm"
}
]
let map = {}
ex.forEach(e => {
let obj = null;
if(e.sender instanceof Object)
obj = e.sender;
else if(e.receiver instanceof Object)
obj = e.receiver;
if(!obj) return;
let key = obj.name+obj.age+obj.city;
if(!map[key])
map[key] = e;
});
console.log(Object.values(map));
answered Sep 5, 2020 at 19:52
Majed Badawi
28.5k4 gold badges30 silver badges56 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Similoluwa Odeyemi
Thanks for your response, what if I still want to have it in array. Lets say there's a possibility of have several scenarios like that
Majed Badawi
@SimiloluwaOdeyemi
Object.values(map) is another array containing the new unique elements.Explore related questions
See similar questions with these tags.
lang-js