Home > OS >  Get values from array of objects, inside an object
Get values from array of objects, inside an object

Time:09-24

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']

CodePudding user response:

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.

CodePudding user response:

Assuming dia is a typo:

const days = [];
for (let p of partys.days) {
  days.push(p.day);
}
console.log(days)
  • Related