Reputation: 383
I have an object that I would like to filter and only return the objects where salesPersonID = "1"
var jsonData = {
"a": {
"id": "a",
"name": "Lucifer Enterprises",
"salesPersonId": "1"
},
"b": {
"id": "b",
"name": "Charlies Chocolate Factory",
"salesPersonId": "1"
},
"c": {
"id": "c",
"name": "Geckos Investments",
"salesPersonId": "2"
}
};
Expected output:
var jsonDataFiltered = {
"a": {
"id": "a",
"name": "Lucifer Enterprises",
"salesPersonId": "1"
},
"b": {
"id": "b",
"name": "Charlies Chocolate Factory",
"salesPersonId": "1"
}
};
What I have tried
var filteredJsonData = jsonData.filter(function (row){
console.log("test");
});
var filteredJsonData = Object.entries(jsonData).filter(function (entry){
return entry[1].salesPersonId == "1";
});
Output from test 2 which has the right values but the wrong structure:
[
[ "a", { "id": "a", "name": "Lucifer Enterprises", "salesPersonId": "1" } ],
[ "b", { "id": "b", "name": "Charlies Chocolate Factory", "salesPersonId": "1" } ]
]
The question
How can I get the desired output?
Upvotes: 3
Views: 101
Reputation: 28434
You can use Object.fromEntries
:
var jsonData = {
"a": {
"id": "a",
"name": "Lucifer Enterprises",
"salesPersonId": "1"
},
"b": {
"id": "b",
"name": "Charlies Chocolate Factory",
"salesPersonId": "1"
},
"c": {
"id": "c",
"name": "Geckos Investments",
"salesPersonId": "2"
}
};
var filteredJsonData = Object.fromEntries(Object.entries(jsonData).filter(function (entry){
return entry[1].salesPersonId == "1";
}));
console.log(filteredJsonData);
Upvotes: 2