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.

4
  • 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 on that item Commented Jan 9, 2018 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. Commented Jan 9, 2018 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. Commented Jan 9, 2018 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 Commented Jan 9, 2018 at 22:00

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.