0

As the title states, I am trying to return an array containing the value associated with that key for each object, or undefined if that key is not present.

Here is what I have so far:

function pluck(arr, name) {

permittedValues = arr.map(function(value) {
  return value.key || undefined;
});
}
console.log(
  pluck([
  { name: "Tim" }, { name: "Matt" }, { name: "Elie" }],
 'name'
)
  );

I am trying to return something like this:

// ["Tim", "Matt", "Elie"]
4
  • 2
    value[name] would be the array syntax Commented Dec 30, 2019 at 18:24
  • 2
    well pluck returns nothing and what is key? Commented Dec 30, 2019 at 18:24
  • 1
    value.key is the property named key, not the property named whatever the value of key is. See e.g. stackoverflow.com/q/4841254/3001761. Commented Dec 30, 2019 at 18:26
  • You have no variable named key. Did you mean to write function pluck(arr, key)? Commented Dec 30, 2019 at 18:30

2 Answers 2

2

You can use indexer to get the property and if it doesn't exist, undefined will be returned:

function pluck(arr, name) {
    return arr.map(function (value) {
        return value[name];
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to return value[name] || undefined, if name key doesn't exist it will return undefined anyway.

function pluck(arr, name) {

return permittedValues = arr.map(value => 
  value[name]);
}
console.log(
  pluck([
  { name: "Tim" }, { name: "Matt" }, { name: "Elie" }],
 'name'
)
  );

This code can get even more concise using arrow functions

const pluck = (arr, name) => arr.map(value => value[name])

console.log(pluck([{ name: "Tim" }, { name: "Matt" }, { name: "Elie" }],'name'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.