-3

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?

3

4 Answers 4

3

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}`}))
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

0

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

Comments

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

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.