将数组转换为另一个自定义数组 - javascript
Convert array to another custom array - javascript
我有数组
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
我需要将其转换为
const array2 = [
{ name: "1-A" },
{ name: "2-B" },
];
我该怎么做?
您可以使用Array.map
方法。 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}`}))
你循环并分配新值。
多种方式之一:
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
const array2 = array1.map(element => {
return {
name: `${element.count}-${element.category}`
}
});
console.log(array2)
作为 Array.map 的替代方法,您可以使用 foreach / push。
您可以在 forEach 的回调函数中进行更多控制。
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
let array2 =[]
array1.forEach( (data) =>
{
array2.push({name : `${data.count}-${data.category}`})
})
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 });
}
我有数组
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
我需要将其转换为
const array2 = [
{ name: "1-A" },
{ name: "2-B" },
];
我该怎么做?
您可以使用Array.map
方法。 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}`}))
你循环并分配新值。
多种方式之一:
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
const array2 = array1.map(element => {
return {
name: `${element.count}-${element.category}`
}
});
console.log(array2)
作为 Array.map 的替代方法,您可以使用 foreach / push。 您可以在 forEach 的回调函数中进行更多控制。
const array1 = [
{ count: "1", category: "A" },
{ count: "2", category: "B" },
];
let array2 =[]
array1.forEach( (data) =>
{
array2.push({name : `${data.count}-${data.category}`})
})
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 });
}