var testObject = {
address: { form: 1, status: "VALID" },
address2: {form: 1, status: "INVALID" },
address3: {form: 1, status: "INVALID" }
}
Object.keys(testObject)
.filter(key => console.log(key))
What I'm trying to do here is to filter the data based on the status INVALID.
example output should be like this.
{
address2: { form: 1, status: "INVALID" },
address3: { form: 1, status: "INVALID" }
}
or
[
{ address2: { form: 1, status: "INVALID" } },
{ address3: { form: 1, status: "INVALID" } }
]
One liner:
Object.fromEntries(Object.entries(testObject).filter(x => x[1].status === "INVALID"))
Long:
const objectConvertedToArray = Object.entries(testObject)
const filteredArray = objectConvertedToArray.filter(([key, val] => val === "INVALID"))
const filteredObject = Object.fromEntries(filteredArray)
Loop over the Object.entries and add the properties that match to a new object.
var testObject = {
address: { form: 1, status: "VALID" },
address2: { form: 1, status: "INVALID" },
address3: { form: 1, status: "INVALID" }
}
const out = {};
for (let [key, obj] of Object.entries(testObject)) {
if (obj.status === 'INVALID') out[key] = obj;
}
console.log(out);
If you want an array push the object on to an array using the key.
var testObject = {
address: { form: 1, status: "VALID" },
address2: { form: 1, status: "INVALID" },
address3: { form: 1, status: "INVALID" }
}
const out = [];
for (let [key, obj] of Object.entries(testObject)) {
if (obj.status === 'INVALID') out.push({ [key]: obj });
}
console.log(out);
This should do the trick without changing the original object:
var testObject = {
address: { form: 1, status: "VALID" },
address2: {form: 1, status: "INVALID" },
address3: {form: 1, status: "INVALID" }
}
var ouput = Object.keys(testObject).reduce((obj, element) => {
if(testObject[element].status === 'INVALID') obj[element] = testObject[element]
return obj
}, {})
console.log(ouput)