skip to Main Content

I am using Jquery to read a JSON file and am filtering select items from that file into a new array.

The JSON file looks like:

[
  {
    "id": "1234",
    "label": "Product 1",
    "price": "140"
  },
  {
    "id": "5678",
    "label": "Product 2",
    "price": "199"
  },
  {
    "id": "9012",
    "label": "Product 3",
    "price": "500"
  },
  // etc
]

I am using the following code to retrieve the data I want:

const activeProdIDs = [
  1234,
  9012
];

let filteredJson = [];

 $.ajax({
        url: dataURL,
        type: "GET",
        dataType: "json",
        success: function (myJson) {
            
            activeProdIDs.forEach(function(prodID) {
                filteredJson.push(myJson.filter(item => item.id == prodID));
            });

            console.log(filteredJson);

    },
    error: function () {
        console.log("Something went wrong");
    },
});

And this works, but the array that is returned has an extra level/layer to it:

[
    [
        {
        "id": "1234",
        "label": "Product 1",
        "price": "140"
        }
    ],
    [
        {
        "id": "9012",
        "label": "Product 3",
        "price": "500"
        }
    ],
    //etc
]

So instead of accessing a product’s label like filteredJson[0].label I must do filteredJson[0][0].label.

Would anyone know why the filter is pushing the JSON objects as their own array ane what I could do to fix this?

(This also seems to happen if I add the JSON objects to another object instead of an array).

2

Answers


  1. The problem is that Array.prototype.filter() returns an array where you’re only looking for single elements.

    You could use Array.prototype.find() instead but I would suggest sticking with filter() and using a Set of IDs for more performant lookups

    const ids = new Set(activeProdIDs.map(String)); // match types
    const filteredJson = myJson.filter(({ id }) => ids.has(id));
    

    Note: this will return matching records in the order they appear in myJson. Your original code returns records in the order the IDs appear in activeProdIDs so if this is a problem, please make that clear.

    Login or Signup to reply.
  2. You need to use find function in this case:

    filteredJson = activeProdIDs.map(id => myJson.find(item => item.id == id)).filter(item => item !== undefined)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search