0

I am iterating data from a JSON file that I previousy fetch with the following code:

    getData().then(data => {
                for (const key in data) {
                    if (data.hasOwnProperty(key)) {
                       //  do something with the data
                    }
                }
            }

The json file is very long, but it look something like this:

{ 
  "01": {
     "id" : "01",
     "title" : "example1",
     "size" : "100",
     "pictures" : []
  },
  "02": {
     "id" : "02",
     "title" : "example2",
     "size" : "0",
     "pictures" : []
  },
  "03": {
     "id" : "03",
     "title" : "example3",
     "size" : "300",
     "pictures" : [
       { "pic_name1" : "example_pic1", "source" : "http://example.pic/1234" },
       { "pic_name2" : "example_pic2", "source" : "http://example.pic/4321" },
     ]
  },
  
}

Now, to create a function that will filter through my data I need to put all of the size in a separate array (that I will later work with) and I tried this (inside the IF condition)

let sizes = new Array(data[key].size);

What I need to return is an array, but I get instead a list of array for each size: ["100"]["0"]["300"]...

How do I return a single array with all sizes as a list?

2 Answers 2

1

Simply map over each value and pluck the size. E.g.

const data = {
    "01": {
        "id" : "01",
        "title" : "example1",
        "size" : "100",
        "pictures" : []
    },
    "02": {
        "id" : "02",
        "title" : "example2",
        "size" : "0",
        "pictures" : []
    },
    "03": {
        "id" : "03",
        "title" : "example3",
        "size" : "300",
        "pictures" : [
            { "pic_name1" : "example_pic1", "source" : "http://example.pic/1234" },
            { "pic_name2" : "example_pic2", "source" : "http://example.pic/4321" },
        ]
    },
};

const sizes = Object.values(data).map(({size}) => size);

console.log(sizes);

Sign up to request clarification or add additional context in comments.

Comments

0

Using ES8 new features inside the if condition,

let sizes = Object.values(data).map(({size}) => size);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.