底部是我尝试解析的JSON文件的精简版本。我想创建单个对象,这些对象具有团队名称和球员名称的键。
我该如何使用球队名称并映射到每个单独的球员并收到类似的信息(使用javascript):
[
{ name: 'Dallas Stars', playerName: 'Alexander Radulov'},
{ name: 'Dallas Stars', playerName: 'Ben Bishop'},
{ name: 'Dallas Stars', playerName: 'Jamie Benn'}
...
{ name: 'Columbus Blue Jackets', playerName: 'Pierre-Luc Dubois'}
]
通过此JSON:
[ { name: 'Dallas Stars',
roster:
[ 'Alexander Radulov',
'Ben Bishop',
'Jamie Benn',
'Tyler Pitlick',
'Miro Heiskanen' ] },
{ name: 'Los Angeles Kings',
roster:
[ 'Jonathan Quick',
'Jonny Brodzinski',
'Oscar Fantenberg' ] },
{ name: 'San Jose Sharks',
roster:
[ 'Joe Thornton',
'Brent Burns',
'Joe Pavelski',
'Antti Suomela' ] },
{ name: 'Columbus Blue Jackets',
roster:
[ 'Sonny Milano',
'Brandon Dubinsky',
'Nick Foligno',
'Pierre-Luc Dubois' ] } ]
基本上,我正在尝试将顶级密钥对映射到各个玩家。我也尝试过搜索所有lodash函数,但没有偶然发现正确的方法。
是否可以使用平面地图并多次使用团队名称?
答案 0 :(得分:2)
您需要遍历外部数组项,然后在每个数组内部进行迭代,也遍历roster
。 reduce
通常是将数组非一对一地转换为另一个数组的最合适方法:
const input=[{name:'Dallas Stars',roster:['Alexander Radulov','Ben Bishop','Jamie Benn','Tyler Pitlick','Miro Heiskanen']},{name:'Los Angeles Kings',roster:['Jonathan Quick','Jonny Brodzinski','Oscar Fantenberg']},{name:'San Jose Sharks',roster:['Joe Thornton','Brent Burns','Joe Pavelski','Antti Suomela']},{name:'Columbus Blue Jackets',roster:['Sonny Milano','Brandon Dubinsky','Nick Foligno','Pierre-Luc Dubois']}];
const output = input.reduce((a, { name, roster }) => {
roster.forEach((playerName) => {
a.push({ name, playerName });
});
return a;
}, []);
console.log(output);
答案 1 :(得分:0)
映射原始数组,然后为每个要“映射”的项目映射其花名册并创建所需的对象。最后,由于生成的数组将为2d,因此将其展平:
---
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
name: mssql-entry
namespace: multitenancy
spec:
hosts:
- mssql-master
addresses:
- $outside-db-ip/32
ports:
- number: 2433
name: db
protocol: TCP
location: MESH_EXTERNAL
resolution: STATIC
endpoints:
- address: $outside-db-ip
ports:
tcp: 2433
---
apiVersion: v1
kind: Service
metadata:
name: mssql-master
namespace: multitenancy
labels:
app: v1
spec:
ports:
- port: 2433
targetPort: 2433
protocol: TCP
---
apiVersion: v1
kind: Endpoints
metadata:
name: mssql-master
namespace: multitenancy
subsets:
- addresses:
- ip: $outside-db-ip
ports:
- port: 2433
protocol: TCP