Home > Enterprise >  How to retrieve a value from an object array
How to retrieve a value from an object array

Time:08-04

const ciclos = [{num:1, quality: "poor"},
                {num:2, quality: "normal"},
                {num:3, quality: "excelent"},
            ]

I have this object array and I want to get the numbers of "num" to make some operations.

I thought that trying this, but doesn´t worked.

function add() {
    let result = 1 * ciclos.num[1];
    console.log(result);
}

add()

Im looking forward to get that number and use it.

Thanks in advance!

CodePudding user response:

Your syntax is wrong, index selection ([1]) should be done on ciclos variable (cause it is array).

const ciclos = [{num:1, quality: "poor"},
                {num:2, quality: "normal"},
                {num:3, quality: "excelent"},
            ]

function add() {
    let result = 1 * ciclos[1].num;
    console.log(result);
}

add()

So instead of ciclos.num[1] use ciclos[1].num. Also array indexes starts from 0, so you are selecting second element.

And if you want to do some kind of operation with all numbers, you can loop them:

const ciclos = [{num:1, quality: "poor"},
                {num:2, quality: "normal"},
                {num:3, quality: "excelent"},
            ]

function add() {
    let result = 0;
    for (let element of ciclos) {
      result  = 1 * element.num;
    }
    console.log(result);
}

add()

CodePudding user response:

Make use of Array reduce method.

const ciclos = [{num:1,value:'abc'},{num:2,value:'cde'}]
function add() {
        let result = ciclos.reduce((totalValue,elem)=>totalValue elem.num,0)
        console.log(result);
    }
add()

  • Related