简体   繁体   中英

How to delete a specific element from an array of JavaScript objects?

I am receiving a JSON output from a php file, with a number of objects like so:

[
  { "home_content" : "Nam feugiat sem diam, ut fermentum orci hendrerit sit amet.",
    "home_id" : 2,
    "home_img" : "tech.png",
    "home_title" : "Latest Technologies Development"
  },
  { "home_content" : "לורם לורם",
    "home_id" : 239,
    "home_img" : "http://placehold.it/400",
    "home_title" : "שוק פירות וירקות"
  },
  { "home_content" : "New Item Content",
    "home_id" : 259,
    "home_img" : "http://www.placehold.it/100",
    "home_title" : "New Home Item"
  }
]

In my App I want to delete a certain object, is there a way to recieve its position say by home_id ? or anything that will let me differentiate a certain object from that list

What you have there is an array of objects, so you can just loop through the array until you find the one with the desired home_id :

var index;
for (index = 0; index < array.length; ++index) {
    if (array[index].home_id === 2) {
        array.splice(index, 1); // Removes this entry
        break;                  // Exits the loop
    }
}

What you have is an array (obtained from parsing JSON), so you'll have to find the correct index, and splice it:

function delObjWithHomeId(arr, id) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i].home_id === id) {
            return arr.splice(i,1);
        }
    }
}

What you've posted there is an array of objects. That's an important distinction -- though in javascript, and array is a type of object.

An object, as you see, can have alphanumberic property names (indexes, if you will) that correspond to a data element. An array, by contrast, is numerically indexed, starting at 0. It is a lot like an object, but the property names are all numbers, and all in sequential order.

So, imagine your data like this:

{
0:{ 
home_id: 2
home_title: Latest Technologies Development
home_img: tech.png
home_content: Nam feugiat sem diam, ut fermentum orci hendrerit sit amet.
},
1:{ 
home_id: 239
home_title: שוק פירות וירקות
home_img: http://placehold.it/400
home_content: לורם לורם
},
2:{ 
home_id: 259
home_title: New Home Item
home_img: http://www.placehold.it/100
home_content: New Item Content
}
}

You can use a number of methods to manipulate an array, like push() , pop() , shift() . To access a specific one, you usually wind up looping it (unless you already know the correct index ).

There are several methods to looping an array, while being one of the many possible approaches:

var i = 0;
while(var oneItem = myArray[i++]){
    if (oneItem.home_id == theItemIdIAmLookingFor) {
        myArray.splice(i, 1);
        break;
    }
}

Documentation

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