JS- FIlter the JSON accordingly

My Input is:

[   {Value: "My_name", Status: "Done"},   {Value: "My_lastName", Status: "Not_Done"} ] 

The O/P expected is:

{   Value: ["My_name", "My_lastName"]   Status: ["Done", "Not_Done"] } 
Professor Asked on October 26, 2020 in Android langue.
Add Comment
3 Answer(s)

    You can achieve this with reduce method:

    var data =[{Tag: "My_name", Clearance: "Done"},{Tag: "My_lastName", Clearance: "Not_Done"}];  result = data.reduce((acc,elem)=>{    Object.entries(elem).forEach(([k,v])=>{      acc[k] = acc[k] || [];      acc[k].push(v);       })    return acc;  },{});    console.log(result)

    Professor Answered on October 26, 2020.
    Add Comment

      You could do something like this:

      let input = [     {Tag: "My_name", Clearance: "Done"},     {Tag: "My_lastName", Clearance: "Not_Done"} ]; let output = {};  input.forEach((inputObj) => {     Object.keys(inputObj).forEach((key) => {         output[key] = output[key] || [];         output[key].push(inputObj[key]);     }); }); 
      Professor Answered on October 26, 2020.
      Add Comment

        You can use method Object.entries to create enumerable string-keyed property [key, value] pairs and then just use reduce method to fill array:

        const arrayOfEntries = data.flatMap(s => (Object.entries(s))); const result = arrayOfEntries.reduce((a, [k, v]) =>      (a[k] = a[k] || [], a[k].push(v), a), {}) 

        An example:

        const data =[{Tag: "My_name", Clearance: "Done"},      {Tag: "My_lastName", Clearance: "Not_Done"}];    const arrayOfEntries = data.flatMap(s => (Object.entries(s)));  const result = arrayOfEntries.reduce((a, [k, v]) =>       (a[k] = a[k] || [], a[k].push(v), a), {})  console.log(result)

        Professor Answered on October 26, 2020.
        Add Comment

        Your Answer

        By posting your answer, you agree to the privacy policy and terms of service.