简体   繁体   中英

Removing specific duplicates from an array Javascript

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM