Accessing different objects within an array

0

How can I access this object in 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] .cor I will have the% return% and vermelha

How can I always bring color azul ?

    
asked by anonymous 20.07.2017 / 03:11

1 answer

1

You simply filter your object with the condition you want. If in this case you need all objects that have cor: azul , just do:

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

See 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 this 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);
    
20.07.2017 / 03:53