Home > Enterprise >  How to convert Object value to array and add new value
How to convert Object value to array and add new value

Time:10-07

I would like to know how I can convert Object value to array and add value to this array. For example: I have object

const object = {
 names: "John"
}

How can I convert this names from string to array, like this

const namesFromApi = ['Ken', 'Ben', 'Joana', 'Fillip']

namesFromApi.map(el => {
object.names = [names, el]
})

And add new name to my new array from string value

CodePudding user response:

You mean this? Using the spread operator and square brackets to concatenate the names

const object = {
 names: "John"
}
const namesFromApi = ['Ken', 'Ben', 'Joana', 'Fillip']

object.names = [object.names,...namesFromApi]

console.log(object)

CodePudding user response:

If you want to create a new array, you can use:

const object = {
    names: "John"
}
const newObj = [object.names];

const namesFromApi = ['Ken', 'Ben', 'Joana', 'Fillip'];
namesFromApi.forEach(el => {
newObj.push(el);
});
  • Related