2

I would like to delete an object from a JSON objects array. Here is the array:

var standardRatingArray = [
    { "Q": "Meal",
      "type": "stars"
    },
    { "Q": "Drinks",
      "type": "stars"
    },
    { "Q": "Cleanliness",
      "type": "stars"
    }
];

For example how can I delete the object whose key is "Q": "Drinks" ? Preferably of course without iterating the array.

Thanks in advance.

David Faizulaev
  • 4,651
  • 21
  • 74
  • 124
  • 1
    Without iterating the array? The only way is to know the index of the object in the array before hand and then use [delete](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) on that item – Patrick Evans Jan 09 '18 at 21:32
  • @PatrickEvans I agree that you'll need the index beforehand to avoid iteration, but using the delete operator will leave a "hole" in the array (and the arrays length won't change). Probably better to use `.splice` to remove it. – CRice Jan 09 '18 at 21:35
  • 2
    Just FYI JSON stands for Javascript Object Notation. Which is a way to store a javascript object as a string. Your example is a plain array containing objects, not JSON. – Marie Jan 09 '18 at 21:36
  • @CRice, you are correct, i was mistaken and read the question wrong thinking they were wanting to delete the property not the array item – Patrick Evans Jan 09 '18 at 22:00

1 Answers1

13

You have to find the index of the item to remove, so you'll always have to iterate the array, at least partially. In ES6, I would do it like this:

const standardRatingArray = [
    { "Q": "Meal",
      "type": "stars"
    },
    { "Q": "Drinks",
      "type": "stars"
    },
    { "Q": "Cleanliness",
      "type": "stars"
    }
];

const index = standardRatingArray.findIndex(x => x.Q === "Drinks");

if (index !== undefined) standardRatingArray.splice(index, 1);

console.log("After removal:", standardRatingArray);
CRice
  • 29,968
  • 4
  • 57
  • 70