'Convert array to another custom array - javascript

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?



Solution 1:[1]

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}`}))

Solution 2:[2]

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)

Solution 3:[3]

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}`})
})

Solution 4:[4]

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 });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amats
Solution 2 Dom
Solution 3 Vollfeiw
Solution 4