skip to Main Content

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

3

Answers


  1. You can try using map() with filter() like the following way:

    let data = [{"variant_name":"Size","variant_options":["S","M","L","a"]}];
    
    let res = data.map(item => ({
      ...item,
      variant_options: item.variant_options.filter(op => op !== 'S')
    }));
    
    console.log(res);
    Login or Signup to reply.
  2. //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"]}]'>
    Login or Signup to reply.
  3. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search