-1

I have Given this JSON structure:

[{"variant_name":"Size","variant_options":["S","M","L","a"]}]

How would you delete an object from the array by key/value? Let's say I wish to delete the element with variant_options = S, how to get this result:

[{"variant_name":"Size","variant_options":["M","L","a"]}]

I tried but did't get any result

1
  • 2
    Given this JSON structure: parse it first, then you're just dealing with an array with a single object in it - far simpler than dealing directly with a JSON string Commented Dec 30, 2023 at 6:57

2 Answers 2

1

To delete an item from an array in-place:

  1. find its index with Array::indexOf()
  2. remove it by the index with Array::splice()

const products = [{"variant_name":"Size","variant_options":["S","M","L","a"]}, {"variant_name":"Size","variant_options":["S","M","L","a"]}];

const removeSize = (product, size) => {
  const idx = product.variant_options.indexOf(size);
  idx >= 0 && product.variant_options.splice(idx, 1);
};

products.forEach(p => removeSize(p, 'S'));

console.log(JSON.stringify(products));

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

Comments

0

//get json value from your input
let data = $('#your-input-id').val();

//convert array to json
var parsedTest = JSON.parse(data);

let res = parsedTest.map(val => ({val,
  variant_options: val.variant_options.filter(v_o => v_o !== "S")
}));
console.log(JSON.stringify(res))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="your-input-id" name="your-input-id" value='[{"variant_name":"Size","variant_options":["S","M","L","a"]}]'>

1 Comment

JQuery really should not be used for something as simple as this, it's so much bloat for so little

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.