How can I tell if an object is a subset of another Array object?

problem description

provides an object to determine whether it is a subset of another Array object

related codes

provide an object:

{
    name: "",
    age: "12",
    sex: ""
}

determine whether he is a subset of the following Array objects:

[
    {
        name: "",
        age: "10",
        sex: ""
    },
    {
        name: "",
        age: "11",
        sex: ""
    },
    {
        name: "",
        age: "12",
        sex: ""
    }
]
Feb.03,2022

var list = [
            {
                name: '',
                age: '10',
                sex: ''
            },
            {
                name: '',
                age: '11',
                sex: ''
            },
            {
                name: '',
                age: '12',
                sex: ''
            }
        ];
        var child = {
            name: '',
            age: '12',
            sex: ''
        };
        var status = false;//
        list.forEach(function( val , i ){
            if(JSON.stringify(child)===JSON.stringify(val)){
                status = true;
            }
        })

  • if you provide a shallow copy relationship between the object and the elements in the Array, you can use Array.prototype.indexOf directly
  • .
  • if you provide a deep-copy relationship between the object and the element in the Array, you can try to see if the element has unique identifying attributes, such as id , and then use Array.prototype.find or maintain hashmap to check
  • if you do not have uniquely identifiable attributes or there are multiple attributes, you can consider using the JSON.stringify method or providing a toString method for literal comparison

recommend lodash

Previous: < meta name= "viewport" content= "width=980" > is not valid in Wechat and safari

Next: How does hashmap ensure visibility?

Menu