0

I am trying to get the objects name in JS. I am trying to avoid doing loops for better code reading. As I am new to the JS code I am not sure what to do.

const collection = [
        {
        name: 'foo',
        value: 12,
        },
        {
        name: 'bar',
        value: 5,
        },
    ]

const fa = (collection) = {
        //theName should return just the name value so 'bar'
        let theName = Object.keys(collection).find(value => value < 10).name;
        console.log(theName);
}

Thanks to anyone who could help.

4
  • What should be your desired result/output? Commented May 4, 2021 at 7:59
  • 1
    fa = collection => collection.find(({ value }) => value < 10)?.name ? Commented May 4, 2021 at 8:02
  • Hi! Please take the tour (you get a badge!), have a look around, and read through the help center, in particular How do I ask a good question? I also recommend Jon Skeet's Writing the Perfect Question. I'm afraid it's not at all clear what you're asking here. Commented May 4, 2021 at 8:02
  • Thanks. I´ve edited the post and allready I see answers that were needed! Thanks guys! Commented May 4, 2021 at 8:06

2 Answers 2

4

You could get from the array the ones who have a certain value and the get the names from the array.

const
    collection = [{ name: 'foo', value: 12 }, { name: 'bar', value: 5 }],
    fa = collection => collection
        .filter(({ value }) => value < 10)
        .map(({ name }) => name);

console.log(fa(collection));

If you want only a single/first result, you could find the object and get the name from it with an optional chaining operator ?. to prevent using a property on undefined.

const
    collection = [{ name: 'foo', value: 12 }, { name: 'bar', value: 5 }],
    fa = collection => collection
        .find(({ value }) => value < 10)
        ?.name;

console.log(fa(collection));

Sign up to request clarification or add additional context in comments.

Comments

2

You probably wanted this:

const collection = [
        {
        name: 'foo',
        value: 12,
        },
        {
        name: 'bar',
        value: 5,
        },
    ]

const fa = (collection) => {
    let theName = collection.find(obj => obj.value < 10).name;
    console.log(theName);
}
fa(collection)

2 Comments

yes, but use ?.name instead of .name in case it's not there
@georg you're right, but intentionally I didn't used optional chaining operator, since it's still quite modern feature, and we also expect that every collection will have name and value.

Your Answer

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.