Home > OS >  How can I remove the key from an array but keeping the value in the array?
How can I remove the key from an array but keeping the value in the array?

Time:09-08

I have an array like this:

language: 
 [
   {added: "English"}
 ]

What I want to do is to remove the key added but I want to keep the value English in the same array.

The result I except:

language: 
 [
  "English"
 ]

By far I have tried something like this:

for(let i  in language) {
 delete language[i].added
}
console.log(language)

This will remove the key and the value as well. How can I remove the key, but keep the value in the same array?

CodePudding user response:

If the objects just consist of a single property, added, you can use Array.map to convert the objects into scalar values:

data = {
  language: [
    { added: "English" }
  ]
}

data.language = data.language.map(o => o.added)

console.log(data)

CodePudding user response:

You aren't deleting a key, you're replacing an entry in an array. The old entry is an object with a single key and the new one is it's value:

 language = [
   {added: "English"}
 ]
 
for (let i in language) {
  language[i] = Object.values(language[i])[0]
}
 
 console.log(language);

  • Related