0
const a=[{name:'ee'},{name:"ddsf"}]
const b=a.map(({name})=>{
  if(name!='ee')
  return {
    key:'dd',
    name:name +'sss'
  }
})

console.log(b)

I am getting

[undefined, [object Object] {
  key: "dd",
  name: "ddsfsss"
}]

why undefined ?

Expected output

[[object Object] {
  key: "dd",
  name: "ddsfsss"
}]

here is code https://jsbin.com/wujekavivo/edit?html,js,console,output

1
  • 3
    Because you return nothing if name is equal to ee. Commented Mar 6, 2019 at 0:40

2 Answers 2

1

The map function returns an array that has correspondence with the array you iterate to. So the undefined value corresponds to the first item in the array with name: 'ee'. If you just want to get those with name !== 'ee', you can just use filter instead. Or better yet you can do:

a.reduce((arr, {name}) => {
  if(name === 'ee') {
    arr.push({
      key: 'dd',
      name: name + 'sss',
    });
  }
  return arr;
}, []);

Unlike map, reduce you pretty much have more control.

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

Comments

1

You want .filter before .map.

const b = a.filter(o => o.name != 'ee')
  .map(o => ({
      key: 'dd',
      name: o.name + 'sss'
    })
  );

This is because .map always returns an array of length equal to the original. By filtering first, you're reducing it down to the desired set.

You can also use .reduce() to accomplish both at once.

const b = a.reduce((o, acc) => 
    o.name == 'ee' ? acc : acc.concat({
      key: 'dd',
      name: o.name + 'sss'
    })
, []);

Comments

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.