MasterSmack
MasterSmack

Reputation: 383

Javascript: Filter object returns the right values but with the wrong structure

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

  1. Using filter directly on the object which results in Uncaught TypeError: jsonData.filter is not a function
      var filteredJsonData = jsonData.filter(function (row){
        console.log("test");
      });
  1. Using Object entries and filter which returns a and b but with a different structure that will be an issue for what I am using the object for down the line.
      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

Answers (1)

Majed Badawi
Majed Badawi

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

Related Questions