It is a simple javascript problem and i am unable to get my head through it
const jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
]
let result = jsObjects.find(obj => {
return obj.b === 6
})
console.log(result)
i just want to console the entire list of 'b' rather than find a single variable 'b' which holds value 6
is there any way to do that
Harun Or Rashid
5,9572 gold badges21 silver badges23 bronze badges
2 Answers 2
You can use Array.filter() instead of Array.find()
const jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
]
let result = jsObjects.filter(obj => obj.b === 6)
console.log(result)
UPDATE
If you want to take only one property, then you can use Array.map()
const jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
]
let result = jsObjects.map(obj => obj.b)
console.log(result);
answered Nov 4, 2019 at 11:31
Harun Yilmaz
8,5893 gold badges30 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
juhi
i need the output like this: {b: 2, b:4, b:6, b:8} how can i get this?
Harun Yilmaz
Your desired output is not a valid object structure as it holds different values for same key. If you need to get them as array, please see updated answer
If you still want them as objects in an array, you can update Harun's code like this:
let myBs = [];
let result = jsObjects.map(obj => myBs.push({b: obj.b}));
console.log(myBs);```
answered Nov 4, 2019 at 12:02
zimmerbimmer
95810 silver badges27 bronze badges
Comments
lang-js
jsObjects.filter(obj => obj.b === 6);let out = jsObjects.map(e => e.b)