getCardList() {
this.http
.get<CardList>
(BACKEND_IP + CARD_LIST)
.subscribe(data => {
console.log(data);
this.cardList = data;
console.log(this.cardList);
return this.cardList;
});
return this.cardList;
}
我从后端得到答案:
0:
mass: (2) [25, 50]
name: "Tanks"
__proto__: Object
1:
mass: (2) [10, 15]
name: "Car"
__proto__: Object
----------
如何获取数组格式
mass: (25)
name: "Tanks"
mass: (50)
name: "Tanks"
mass: (10)
name: "Car"
mass: (15)
name: "Car"
通过this.cardList.map
答案 0 :(得分:2)
您可以map
所需的对象,然后通过flatMap
方法将数据平坦:
const arr = [
{ mass: [25, 50], name: "Tanks" },
{ mass: [10, 15], name: "Car" }
];
const result = arr.flatMap(a => a.mass.map(s=> ({mass: s, name: a.name})));
console.log(result);
答案 1 :(得分:1)
尝试解决方案
let cardList = [{mass: [25,50], name: 'tank'}, {mass: [10,15], name: 'Car'}]
const res = cardList.map(({mass, name})=> {
return mass.map(m => ({mass: m, name}))
}).flat()
console.log(res)
答案 2 :(得分:0)
这是使用map
和reduce
的解决方案:
const cardList = [
{ mass: [25, 50], name: 'Tanks' },
{ mass: [10, 15], name: 'Car' }
];
const out = cardList.reduce((acc, c) => {
// Destructure the mass and name
// from the current object
const { mass, name } = c;
// Create a new array of objects by mapping
// over the mass array and creating a new object for each
const temp = mass.map((n) => ({ mass: n, name }));
// Spread out the new array and concatentate
// to the accumulator
return acc.concat(...temp);
}, []);
console.log(out);
答案 3 :(得分:0)
let list = [
{'mass': [25, 50], 'name': 'Tanks'},
{'mass': [10, 15], 'name': 'Car'}
];
let result = list.reduce((acc, o) => (acc.push(...[...o.mass.map(v => ({'mass': v, 'name': o.name}))]), acc) , []);
console.log(result);
答案 4 :(得分:0)
由于您已使用Angular对此进行了标记,因此我假设您正在将Observables与rxjs一起使用。我可以使用map和map和flat的JavaScript运算符
getCardList() {
return this.http
.get<CardList>
(BACKEND_IP + CARD_LIST).pipe(
map(result => {
// conversion routine borrowed for @Harish
const newArray = result.map(({mass, name})=> {
return mass.map(m => ({mass: m, name}))
}).flat()
return newArray;
}
)
.subscribe(data => {
console.log(data);
});
}
我还从subscribe()
内部取出了您的退货,因为订阅不需要退货。我还从方法而不是this.cardlist
返回了observable;因为在异步服务返回结果之前,此方法将返回一个空数组或未初始化的值。