0

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
asked Nov 4, 2019 at 11:30
2
  • 2
    jsObjects.filter(obj => obj.b === 6); Commented Nov 4, 2019 at 11:31
  • 1
    let out = jsObjects.map(e => e.b) Commented Nov 4, 2019 at 11:34

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

i need the output like this: {b: 2, b:4, b:6, b:8} how can i get this?
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
0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.