-3

I have the following object:

[{
    "id": 2,
    "price": 2000,
    "name": "Mr Robot T1",
    "image": "http://placehold.it/270x335"
}, {
    "id": 1,
    "price": 1000,
    "name": "Mr Robot T2",
    "image": "http://placehold.it/270x335"
}]

and what I want is to remove the first item (id = 1) and the result is:

[{
    "id": 2,
    "price": 2000,
    "name": "Mr Robot T1",
    "image": "http://placehold.it/270x335"
}]

as it could do?

Alfredo Solís
  • 448
  • 2
  • 5
  • 14
  • 2
    Go to MDN and read about Array.prototype. Don't run to stackoverflow asking such basic questions. Also this has *nothing* to do with jquery. – Azamantes Sep 25 '16 at 02:19
  • You have an array of objects, not just an object. You are asking to remove one indexed item in an array. See: [`Array.prototype.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) – Makyen Sep 25 '16 at 02:20
  • Bonsoir Elliot : `array.splice(0,1)` – jrbedard Sep 25 '16 at 02:21
  • @mayken I'll try that function – Alfredo Solís Sep 25 '16 at 02:25

1 Answers1

0

Something like the following code?

var array = [{
    "id": 2,
    "price": 2000,
    "name": "Mr Robot T1",
    "image": "http://placehold.it/270x335"
}, {
    "id": 1,
    "price": 1000,
    "name": "Mr Robot T2",
    "image": "http://placehold.it/270x335"
}];

var newArray = [];

array.forEach(function(item){
    if (item.id != 1) {
        newArray.push(item);
    }
});

Basically that will loop through your array and all elements that don't have an id = 1 will get pushed to the variable newArray.

EDIT

In order to delete the item you can always splice it. Something like the following.

var array = [{
    "id": 2,
    "price": 2000,
    "name": "Mr Robot T1",
    "image": "http://placehold.it/270x335"
}, {
    "id": 1,
    "price": 1000,
    "name": "Mr Robot T2",
    "image": "http://placehold.it/270x335"
}];

array.forEach(function(item, index){
    if (item.id == 1) {
        array.splice(index, 1);
    }
});
Charlie Fish
  • 13,172
  • 14
  • 64
  • 137