如何用键值对构造字符串数据
How to structure string data with key value pair
我需要的结构:
[{ label:'Year',
type:'year',
options:[{ year:'2019' },{ year:'2018' },{ year:'2017' },{ year:'2016' }] },
{ label:'Make',
type:'make',
options:[{ make:'Ford' },{ make:'BMW' }] },
{ label:'Model',
type:'model',
options:[{ model:'Freestyle' },{ model:'Mustang' }] },
{ label:'Location',
type:'location',
options:[{ location:'Manheim' },{ location:'Adessa' },{ location:'Manheim, Georgia' }] }]
我得到的服务数据是:
{ location: ["Manheim", "Adessa"],
model: ["Lincoln", "Ford"],
series: ["s-160", "B-140"],
year: ["2019", "2018", "2017"] }
请帮我找出我需要的结构
您可以 map
每个 属性 源结构到您的目标结构。要动态访问 options
的属性,属性应该是文字而不是 string
。因此你可以使用 as const
.
const src = {
location: ["Manheim", "Adessa"],
model: ["Lincoln", "Ford"],
series: ["s-160", "B-140"],
year: ["2019", "2018", "2017"]
}
const keys = ['location', 'model', 'series', 'year'] as const
const result = keys.map((e) => ({
label: e.replace(/^./, (c) => c.toUpperCase()),
options: src[e].map((o) => ({ [e]: o })),
type: e
}))
我需要的结构:
[{ label:'Year',
type:'year',
options:[{ year:'2019' },{ year:'2018' },{ year:'2017' },{ year:'2016' }] },
{ label:'Make',
type:'make',
options:[{ make:'Ford' },{ make:'BMW' }] },
{ label:'Model',
type:'model',
options:[{ model:'Freestyle' },{ model:'Mustang' }] },
{ label:'Location',
type:'location',
options:[{ location:'Manheim' },{ location:'Adessa' },{ location:'Manheim, Georgia' }] }]
我得到的服务数据是:
{ location: ["Manheim", "Adessa"],
model: ["Lincoln", "Ford"],
series: ["s-160", "B-140"],
year: ["2019", "2018", "2017"] }
请帮我找出我需要的结构
您可以 map
每个 属性 源结构到您的目标结构。要动态访问 options
的属性,属性应该是文字而不是 string
。因此你可以使用 as const
.
const src = {
location: ["Manheim", "Adessa"],
model: ["Lincoln", "Ford"],
series: ["s-160", "B-140"],
year: ["2019", "2018", "2017"]
}
const keys = ['location', 'model', 'series', 'year'] as const
const result = keys.map((e) => ({
label: e.replace(/^./, (c) => c.toUpperCase()),
options: src[e].map((o) => ({ [e]: o })),
type: e
}))