I have the array
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
and I need to convert it to
const array2 = [
{ name: "1-A" },
{ name: "2-B" },
];
How can I do it?
CodePudding user response:
You can use Array.map
method. Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
const array2 = array1.map(item => ({ name : `${item.count}-${item.category}`}))
CodePudding user response:
You loop over and assign new values.
One of many ways:
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
const array2 = array1.map(element => {
return {
name: `${element.count}-${element.category}`
}
});
console.log(array2)
CodePudding user response:
As an alternative to Array.map, you can use foreach / push. You can have more control inside the callback function of forEach.
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
let array2 =[]
array1.forEach( (data) =>
{
array2.push({name : `${data.count}-${data.category}`})
})
CodePudding user response:
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
var array2 = [],
newVar;
for (let index = 0; index < array1.length; index ) {
newVar = array1[index].count "-" array1[index].category;
array2.push({ name: newVar });
}