Reputation: 4296
I have this JSON object :
{
"active": 0,
"0": "active",
"inactive": 1,
"1": "inactive",
"ineligable": 2,
"2": "ineligable",
"error": 3,
"3": "error",
"suspended": 4,
"4": "suspended",
"archived": 5,
"5": "archived",
"removed": 6,
"6": "removed"
}
I want to filter the ones with a numerical value. The thing is I accomplished this already. But in a very ugly way and i wish to know if theres a better way to filter objects than the one I did.
Here's my try :
const statuses = listingstatus; //this is the object
let toFill = [];
Object.keys(statuses).forEach(key => {
if(Number.isInteger(statuses[key])){
toFill.push({[key]: statuses[key]});
};
});
console.log(toFill)
The result is this :
Array :
0: {active: 0}
1: {inactive: 1}
2: {ineligable: 2}
3: {error: 3}
4: {suspended: 4}
5: {archived: 5}
6: {removed: 6}
Upvotes: 0
Views: 61
Reputation: 177
You can try this way:
const statuses = listingstatus
Object.keys(statuses).forEach(key => {
if (isNaN(statuses[key])) delete statuses[key];
});
console.log(statuses)
Upvotes: 0
Reputation: 6714
To still satisfy your requirements you could simplify it by using Object.entries
instead of Object.keys
and reduce the result into a single value with Object.reduce
instead of iterating and pushing onto another variable when necessary
const statuses = {
"active": 0,
"0": "active",
"inactive": 1,
"1": "inactive",
"ineligable": 2,
"2": "ineligable",
"error": 3,
"3": "error",
"suspended": 4,
"4": "suspended",
"archived": 5,
"5": "archived",
"removed": 6,
"6": "removed"
}
const toFill = Object.entries(statuses).reduce((all, [key, value]) => Number.isInteger(value) ? [...all, {[key]:value}] : all,[]);
console.log(toFill)
However i wonder why do you need such a format in the first place, i think it would be better to just return a single object with those values, instead of an array of object, in which case you would do something like:
const statuses = {
"active": 0,
"0": "active",
"inactive": 1,
"1": "inactive",
"ineligable": 2,
"2": "ineligable",
"error": 3,
"3": "error",
"suspended": 4,
"4": "suspended",
"archived": 5,
"5": "archived",
"removed": 6,
"6": "removed"
}
const toFill = Object.entries(statuses).reduce((all, [key, value]) => Number.isInteger(value) ? {...all, [key]:value} : all,{});
console.log(toFill)
Upvotes: 2
Reputation: 12954
Try this, I've used Object.keys
and Array.reduce
:
const obj = {
"active": 0,
"0": "active",
"inactive": 1,
"1": "inactive",
"ineligable": 2,
"2": "ineligable",
"error": 3,
"3": "error",
"suspended": 4,
"4": "suspended",
"archived": 5,
"5": "archived",
"removed": 6,
"6": "removed"
};
const output = Object.keys(obj).reduce((acc, k) => Number.isInteger(obj[k]) ? (acc.push({ [k]: obj[k] }), acc) : acc, []);
console.log(output);
Upvotes: 0