0
let data = [
{"name":"Dhanush","createdAt":"2021/01/13 16:57:53","songs":[]},
{"name":"Dharma","createdAt":"2021/01/13 17:02:47","songs":[]},
{"name":"Sachin","createdAt":"2021/01/13 17:30:45","songs":[]}
]

let name = "Dhanush"

let song = {
  'id':1,
  'duration': '5 mins',
  'name': 'Bingo'
}

Here I need to loop the data array and check if data.name === name , if it s true I need to push the song object to the songs array inside the data.

this means

data = data.map(val => val.name === name ? val.songs = [...val.songs,song] : val.songs)

I tried like this. but it doesn't work.

Your help is much appreciated.

Thanks

1
  • data.songs doesn't refer to anything, you want val.songs Commented Jan 13, 2021 at 18:29

1 Answer 1

1

You are not returning val when using map method.

let data = [
  { name: 'Dhanush', createdAt: '2021/01/13 16:57:53', songs: [] },
  { name: 'Dharma', createdAt: '2021/01/13 17:02:47', songs: [] },
  { name: 'Sachin', createdAt: '2021/01/13 17:30:45', songs: [] },
];

const name = 'Dhanush';

const song = {
  id: 1,
  duration: '5 mins',
  name: 'Bingo',
};
data = data.map(
  (val) => (
    val.name === name ? (val.songs = [...val.songs, song]) : val.songs, val
  )
);
console.log(data);

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

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.