1

What I'm trying to do is read this array of objects below and from there build a list with the free values.

const data = [
  {
      "house01": {
        "free": 6
      },
      "house02": {
        "free": 2
      },
      "house03": {
        "free": 1
      },
  }
]


console.log(data.map((item) => item.free))

Response

[undefined] 

Expected response

[6, 2, 1]

What I don't understand is why the result doesn't go as expected.

1
  • Why is the data structured like that? An array of objects with one object with consecutive numbers as keys. Why nit something like const data = { houses: [{ "free": 6 }, { "free": 2 }] } with an additional houseId property in each house object, if required Commented Apr 30, 2021 at 8:22

1 Answer 1

5

You need two iterations, one for the array and another for the object's values to get the wanted property.

const data = [{ house01: { free: 6 }, house02: { free: 2 }, house03: { free: 1 } }];

console.log(data.flatMap(item => Object.values(item).map(({ free }) => free)));

By having unwanted keys, you need to add a filtering and take the entries to get the key as well.

const
    data = [{ house01: { free: 6 }, house02: { free: 2 }, house03: { free: 1 }, dontcountthisdata: "USA" }],
    unwanted = ['dontcountthisdata'];

console.log(data.flatMap(item => Object
    .entries(item)
    .filter(([key]) => !unwanted.includes(key))
    .map(([, { free }]) => free)
));

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

5 Comments

What if I have an object that I don't want to be counted in this flatmap ()? Something like that: [ { "house01": { "free": 6 }, "house02": { "free": 2 }, "house03": { "free": 1 }, "dontcountthisdata": "USA", } ]
do you have only one or more unwanted properties?
More than one unwanted properties
Thank you so much! Quick question, do you know any functions that return data in the order they appear in the list? When I use this function that you created they appear in a different order from the parent list, for example the right would be [6, 2,1] but something like [2, 6, 1] appears
the keys of an object are usually sorted by index like numbers sorted, first, then strings/other numbers in insertation order and at last symbols in insertation order.

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.