Javascript 节点Js通过JSON键转换JSON
我想过滤以下JSON结果。但我无法转换Javascript 节点Js通过JSON键转换JSON,javascript,arrays,node.js,reactjs,typescript,Javascript,Arrays,Node.js,Reactjs,Typescript,我想过滤以下JSON结果。但我无法转换 const result = [ { id: 'e7a51e2a-384c-41ea-960c-bcd00c797629', type: 'Interstitial (320x480)', country: 'ABC', enabled: true, rank: 1, link: '', }]; 到 这是我的密码 const result = [ { id: 'e7a51e2a-384
const result =
[
{
id: 'e7a51e2a-384c-41ea-960c-bcd00c797629',
type: 'Interstitial (320x480)',
country: 'ABC',
enabled: true,
rank: 1,
link: '',
}];
到
这是我的密码
const result =
[
{
id: 'e7a51e2a-384c-41ea-960c-bcd00c797629',
type: 'Interstitial (320x480)',
country: 'ABC',
enabled: true,
rank: 1,
link: '',
}];
const fields = ['type', 'rank', 'enabled'];
const tranform = Object.assign({}, ...fields
.filter(key => !!result[key]).map(key => ({ [key]: result[key] })));
console.log(tranform);
在上面的代码中,我想提取字段数组中提到的键
期望的结果应该是
[{
"Interstitial (320x480)" : {
"enabled": true,
"rank": 1,
}];
先谢谢你 您可以使用函数
map
和计算属性名来使用变量动态创建键
这是假设字段中的第一个索引是主键,下一个索引是要提取的值
const结果=[{
id:'e7a51e2a-384c-41ea-960c-bcd00c797629',
类型:“填隙式(320x480)”,
国家:“ABC”,
启用:对,
排名:1,
链接:“”,
}],
字段=['type'、'rank'、'enabled'],
[键,…其他]=字段;
const mapped=result.map(o=>({[o[key]]:others.reduce((a,c)=>Object.assign({},a,{[c]:o[c]}),{}));
console.log(映射)代码>检查以下代码段
const结果=[{
id:'e7a51e2a-384c-41ea-960c-bcd00c797629',
类型:“填隙式(320x480)”,
国家:“ABC”,
启用:对,
排名:1,
链接:“”,
}];
const transformed=results.map(结果=>
({[result.type]:{enabled:result.enabled,rank:result.rank}});
console.log(已转换)代码>结果是一个对象数组,所以只需在代码中更改这一行即可
14c14
< .filter(key => !!result[key]).map(key => ({ [key]: result[key] })));
---
> .filter(key => !!result[0][key]).map(key => ({ [key]: result[0][key] })));
const fields=['type','rank','enabled']代码>->
第一个索引是将对象中的下一个索引分组的键吗?结果不是硬编码的,我只是在代码中解释过
14c14
< .filter(key => !!result[key]).map(key => ({ [key]: result[key] })));
---
> .filter(key => !!result[0][key]).map(key => ({ [key]: result[0][key] })));