jarwin
jarwin

Reputation: 668

Remove JSON keys that have an array of object with their values undefined

i have an JSON like this and i want to remove all the keys that have an array of objects with their values undefined.

{
  '2020-07-27': [{ 
    name: "Study",
    time: "11:30 - 12:30",
    week: "monday"
  }],
  '2020-08-01': [{ 
    name: "undefined",
    time: "undefined",
    week: "undefined"
  }],
  '2020-08-03': [{ 
    name: "Study",
    time: "11:30 - 12:30",
    week: "monday"
  }],
  '2020-08-07': [{ 
    name: "undefined",
    time: "undefined",
    week: "undefined"
  }],
}

This is what I want to do

{
  '2020-07-27': [{ 
    name: "Study",
    time: "11:30 - 12:30",
    week: "monday"
  }],
  '2020-08-03': [{ 
    name: "Study",
    time: "11:30 - 12:30",
    week: "monday"
  }]
}

Upvotes: 0

Views: 191

Answers (2)

hgb123
hgb123

Reputation: 14891

You could try these following step:

  • use Object.entries() to transform object to list of key-value pairs (in this case is date and array of one object)
  • iterate through that key-value pairs array, filter and ignore pairs that have the array containing your unwanted object
  • use Object.fromEntries() to transform the key-value pairs back to object

const x = {
  "2020-07-27": [
    {
      name: "Study",
      time: "11:30 - 12:30",
      week: "monday",
    },
  ],
  "2020-08-01": [
    {
      name: "undefined",
      time: "undefined",
      week: "undefined",
    },
  ],
  "2020-08-03": [
    {
      name: "Study",
      time: "11:30 - 12:30",
      week: "monday",
    },
  ],
  "2020-08-07": [
    {
      name: "undefined",
      time: "undefined",
      week: "undefined",
    },
  ],
}

const res = Object.entries(x).filter(
  ([date, array]) =>
    !Object.values(array[0]).every((value) => value === "undefined")
)

console.log(Object.fromEntries(res))

Upvotes: 1

Riddhijain
Riddhijain

Reputation: 497

You can loop through the json and check for each of the key value pair and delete if value is undefined.

  var json= {
              '2020-07-27': [{ 
              name: "Study",
              time: "11:30 - 12:30",
              week: "monday"
            }],
              '2020-08-01': [{ 
              name: "undefined",
              time: "undefined",
              week: "undefined"
            }],
              '2020-08-03': [{ 
              name: "Study",
              time: "11:30 - 12:30",
              week: "monday"
            }],
              '2020-08-07': [{ 
              name: "undefined",
              time: "undefined",
              week: "undefined"
            }],
 }
 
 for (var i in json) {
 obj=json[i][0]
 Object.keys(obj).forEach(key => obj[key] == "undefined" ? delete json[i] : {});
 }
 
  console.log(json)

Upvotes: 1

Related Questions