简体   繁体   中英

Find object index from array

I'm trying to find out selected object index from array

But it always return -1 don't know why?

Here is I'm trying to do

I have following array in which their are multiple objects

var data = [{
  "name": "abc",
  "age": 25,
  "school": "xyz pqr"
},
{
  "name": "abc1",
  "age": 26,
  "school": "xyz pqr"
},
{
  "name": "abc2",
  "age": 27,
  "school": "xyz pqr"
}]

And here is my another array that are selected by user

var dList = [{
  "name": "abc",
  "age": 25,
  "school": "xyz pqr",
  "isChecked": true
}]

Now I want to find out selected object index from data array and remove this object from that array

if (dList.length > 0) {
  for (let i=0; i<dList.length; i++){
    delete dList[i]['isChecked']
    console.log(dList[i])
    console.log(data[0])
    console.log(dList[i] == data[0])
    let index = data.indexOf(dList[i]);
    console.log(index)
    data.splice(index, 1);
  }
}

Here is just a simple implementation:

if (dList.length > 0) {
  for (let i=0; i<dList.length; i++) {
    delete dList[i]['isChecked']
    console.log(dList[i])
    console.log(data[0])
    console.log(JSON.stringify(dList[i]) === JSON.stringify(data[0]))
    let index = data.findIndex(()=>dList[i]);
    console.log(index)
    data.splice(index, 1);
  }
}

Comparing the objects can be done by just converting it into string using JSON.stringify(ObjectName).

Second instead of using indexOf use findIndex . Here is the main difference between indexOf and findIndex .

You can only compare two primitive types only so you will not be able to get the index of the object by comparing it.

You should instead compare some primary key which will be unique for each object inside the array.

 var data = [{ "name": "abc", "age": 25, "school": "xyz pqr" }, { "name": "abc1", "age": 26, "school": "xyz pqr" }, { "name": "abc2", "age": 27, "school": "xyz pqr" }]; var index = data.findIndex(x => x.name=="abc2"); console.log(index); 

this is going to meet your demand, a more universal version,if you got unique id,that is going to be the best choice:

 var data = [{ "name": "abc", "age": 25, "school": "xyz pqr" }, { "name": "abc1", "age": 26, "school": "xyz pqr" }, { "name": "abc2", "age": 27, "school": "xyz pqr" } ]; var dList = [{ "name": "abc", "age": 25, "school": "xyz pqr", "isChecked": true }]; dList.forEach(function(obj) { delete obj.isChecked; data.splice(data.findIndex((o) => { return Object.getOwnPropertyNames(obj).every(p => obj[p] === o[p]); }), 1); }); console.log(data); 

another way:

 var data = [{ "name": "abc", "age": 25, "school": "xyz pqr" }, { "name": "abc1", "age": 26, "school": "xyz pqr" }, { "name": "abc2", "age": 27, "school": "xyz pqr" } ]; var dList = [{ "name": "abc", "age": 25, "school": "xyz pqr", "isChecked": true }]; dList.forEach(function(obj) { delete obj.isChecked; data.splice(data.findIndex((o) => o.name === obj.name && o.age === obj.age && o.school === obj.school && o.school === obj.school), 1); }); console.log(data); 

unrecommended way:

 var data = [{ "name": "abc", "age": 25, "school": "xyz pqr" }, { "name": "abc1", "age": 26, "school": "xyz pqr" }, { "name": "abc2", "age": 27, "school": "xyz pqr" } ]; var dList = [{ "name": "abc", "age": 25, "school": "xyz pqr", "isChecked": true }]; dList.forEach(function(obj) { delete obj.isChecked; data.splice(data.findIndex((o) => JSON.stringify(o) === JSON.stringify(obj)), 1); }); console.log(data); 

You can use this also

 var data = [{ "name": "abc", "age": 25, "school": "xyz pqr" }, { "name": "abc1", "age": 26, "school": "xyz pqr" }, { "name": "abc2", "age": 27, "school": "xyz pqr" }]; var dList = [{ "name": "abc", "age": 25, "school": "xyz pqr", "isChecked": true }] console.log(data.map(function(d){ return d.name; }).indexOf(dList[0].name)); 

You cannot compare two Object Notations(JSON). To compare two JSONs you need to first stringify the object, then JavaScript can compare the two objects for you.

Here is a simple code for you to get what you desire.

if (dList.length > 0) {
            for(var i=0; i<data.length; i++){
                for(var j=0; j<dList.length; j++){
                    delete dList[j]['isChecked'];
                    if(JSON.stringify(data[i]) === JSON.stringify(dList[j])){
                        let index = data.indexOf(data[i]);//Gets the index of the array
                        data.splice(index, 1);
                        console.log(data);

                    }else{
                        console.log('Data Not Matched in Array');
                    }
                }
            }
        }

There is no generic means to determine that an object is equal to another in the sense. Please see Equality comparisons for more information.

You can find and remove objects like below:

Array.prototype.remove = function(elem) {
  var indexElement = this.findIndex(el => el.name === elem.name);
  console.log(indexElement);
  if (indexElement != -1)
    this.splice(indexElement, 1);
  return this;
};

data.remove(dList[0]);
console.log(data);

Online demo (jsFiddle)

var result= data.filter((item, i, self) => {
  if (item.name === 'abc2') {
    return { itemIndex: i, obj: item }
  }
});
var output = result.map(r => { console.log(r.itemIndex) })
console.log(output); 

This will return all objects in which name is abc2 . findIndex array method will always return 1 index that might not be the case as people can have the same name.

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