javascriptuppy

how to search json array for value and then erase the index if value is found


I got this json string that I need to parse and remove data from, but I'm unsure of how to go about it. Say I have the following json:

<input 
 name="uppyResult"
 type="hidden"
 value="[{
  &quot;successful&quot;:[
   {&quot;id&quot;:&quot;uppy-a8geo/fw/400x400/jpg-1d-2v-1e-image/jpeg-10097-1626922525568&quot;},
   {&quot;id&quot;:&quot;uppy-maxresdefault/jpg-1e-image/jpeg-81700-1626406845772&quot;}
  ],
  &quot;failed&quot;:[],
  &quot;uploadID&quot;:&quot;ckss6e4xv00023h63uov94n5e&quot;
 }]"
>

I get the element with document.getElementsByName("uppyResult")[0].value; and then I parse it with const obj = JSON.parse(json).

How do I then remove only the index where id: uppy-maxresdefault/jpg-1e-image/jpeg-81700-1626406845772 and reinsert this as a string into the DOM?

Edit: previous version had " instead of &quot; inside value


Solution

  • const data = [{
      "successful":[
       {"id":"uppy-a8geo/fw/400x400/jpg-1d-2v-1e-image/jpeg-10097-1626922525568"},
       {"id":"uppy-maxresdefault/jpg-1e-image/jpeg-81700-1626406845772"}
      ],
      "failed":[],
      "uploadID":"ckss6e4xv00023h63uov94n5e"
     }];
     
    const toRemove = "uppy-maxresdefault/jpg-1e-image/jpeg-81700-1626406845772"; 
    data.forEach(item => {
      Object.values(item).forEach(array => {
        if (!Array.isArray(array))
            return;
        const index = array.findIndex(elm => elm.id === toRemove);
        if (index > -1)
          array.splice(index, 1);
      });
    });
    
    console.log(data);