-1

So, let's say I have this object, and inside of it, I have an array of objects.

let partys = {
    "id": 241,
    "name": "Rock Party",
    "type": "party",
    "days": [
        {
            "id": 201,
            "day": "Monday"
        },
        {
            "id": 202,
            "dia": "Friday"
        }
    ],
}

How do I get only the value of "day"? Like this:

let days = ["Monday", "Friday"]

I've already use Object.values(party.days[0]), but the result is:

[201, 'Monday']

  • 2
    You have two objects, one with a `day` property and one with a `dia` property. If that's a typo, then you can get the answer from https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array – Heretic Monkey Sep 23 '21 at 23:13

3 Answers3

0

let partys = {
    "id": 241,
    "name": "Rock Party",
    "type": "party",
    "days": [
        {
            "id": 201,
            "day": "Monday"
        },
        {
            "id": 202,
            "dia": "Friday"
        }
    ],
};

let days = partys.days.map(x => x.dia || x.day);
console.log(days);

This is the code which works with your data. But really I am sure that the name of the property should be day or dia, not both at the same time.

Alexey Zelenin
  • 710
  • 4
  • 10
0

Assuming dia is a typo:

const days = [];
for (let p of partys.days) {
  days.push(p.day);
}
console.log(days)
kost
  • 705
  • 7
  • 18
-1

You can easily achieve the result using Nullish coalescing operator (??)

partys.days.map((x) => x.dia ?? x.day);

let partys = {
  id: 241,
  name: "Rock Party",
  type: "party",
  days: [
    {
      id: 201,
      day: "Monday",
    },
    {
      id: 202,
      dia: "Friday",
    },
  ],
};

let days = partys.days.map((x) => x.dia ?? x.day);
console.log(days);
DecPK
  • 24,537
  • 6
  • 26
  • 42