How to get all the values associated with an object in array?

Just filter the values and map the desired ones.

array.filter allows you to filter items of an array with a condition, so using i => i.name === 'test0' will return a new array where only the values with name ‘test0’ are acquired. Finally, using map you create a new array, whose values are the result of the callback function provided. So, using map(i => i.value) will return the property .value of each (filtered) object.

If you’re expecting the values to be numeric, remember to cast them to integers.

var array = [
    { name:"test0", value:"0" },
    { name:"test1", value:"1" },
    { name:"test2", value:"2" },
    { name:"test0", value:"3" },
    { name:"test0", value:"4" }
];

var res = array.filter(i => i.name === 'test0').map(i => i.value);
console.log(res);

Otherwise, you can do that in a single shot with reduce:

var array = [
    { name:"test0", value:"0" },
    { name:"test1", value:"1" },
    { name:"test2", value:"2" },
    { name:"test0", value:"3" },
    { name:"test0", value:"4" }
];

var res = array.reduce((a,b) => {
  return b.name === 'test0' && a.push(+b.value), a;
}, []);
console.log(res);

In this last example, the values are casted to integers using the unary operator (+).

Finally, as requested, here is another approach not relying on any array prototype:

var array = [
    { name:"test0", value:"0" },
    { name:"test1", value:"1" },
    { name:"test2", value:"2" },
    { name:"test0", value:"3" },
    { name:"test0", value:"4" }
];

// init a new empty array.
var res = [];
for (var i = 0; i < array.length; i++) {
  var item = array[i]; // not mandatory but easy enough to read: acquire the current looped value.
  if (item.name === 'test0') { // if the looped item name is 'test0', join the if.
    res.push(Number(item.value)); // if so, push the item's value, and cast it to a number (using Number).
  }
}
console.log(res); // log the result.

Leave a Comment