Accessing different objects within an array

Asked

Viewed 325 times

0

How can I access this object the right way? I have these two scenarios

Object
  Array[2]
   Object: {"code": "a", cor: "vermelha"}
   Object: {"code": "b", cor"azul"}

and

Object
  Array[1]
   Object: {"code": "b", cor: "azul" }

if I do hair.property[0]. color I’ll get the return vermelha and azul

how can I always bring color azul?

  • It is unclear what your selection condition is. You need to always take the last element?

  • i need to always bring the object that has the blue color, q in the first scenario is in position [1] and then in position [0]

1 answer

1

Just filter your object on the condition you wish. If in this case you need all the objects you own cor: azul, just do:

let list = cabelo.propriedade.filter(item => {
    return (item.cor == "azul");
});

Take the example:

const cabelo = {
    "propriedade": [
        {
            "code": "a",
            "cor": "vermelha"
        }, {
            "code": "b",
            "cor": "azul"
        }
    ]
};

let list = cabelo.propriedade.filter(item => {
    return (item.cor == "azul");
});

console.log(list);

If there are more records that satisfy such condition, they will all be returned:

const cabelo = {
    "propriedade": [
        {
            "code": "a",
            "cor": "vermelha"
        }, {
            "code": "b",
            "cor": "azul"
        }, {
            "code": "c",
            "cor": "azul"
        }
    ]
};

let list = cabelo.propriedade.filter(item => {
    return (item.cor == "azul");
});

console.log(list);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.