如何获得:借助更大的对象常量数据集中的模板,对象常量数组?

时间:2019-04-17 11:31:13

标签: javascript jquery

是否存在单行,请输入mapfilter ... es5 +更高功能或...? 希望能以解题的方式,原因和解决方案。 如果有人知道为什么曾经不起作用。

timeTableKeys:是输出Template数组,按键顺序。 运行者:对象文字数组。 parseStringify:JSON.parse-带有易于过滤的第二个参数(timeTableKeys)的JSON.stringify。 manualNewObject:手动创建对象文字。 multilineMapNewObj:使用timeTableKeys创建对象文字。

const runers = [{'Name':'Joe Bennet', 'Seasons':3, 'Time':'46m:12s:431ms', 'Place':12, 'Age':46, 'Gender':'M', 'Qual':'Pre', 'State':'TX', 'Adress':'Little Cow Middle Town, 2nd Main 5th Street 14C App 38','Mail':'joeB46TX@littelecowMT.org','Phone':'555-1845-LCMT','Group':'Semi-Senior', 'Doping-Test':'Passed', 'NR':7289},{'Name':'Allan Jenkin', 'Seasons':5, 'Time':'52m:29s:894ms', 'Place':153, 'Age':52, 'Gender':'M', 'Qual':'2nd Heat', 'State':'CA', 'Adress':'Redmond River, Downunder H12C ','Mail':'senior.jenkinA@qwredmond.net','Phone':'555-327-REDMOND','Group':'Semi-Senior', 'Doping-Test':'Passed', 'NR':925}],
timeTableKeys = ['State','Name','NR','Place','Time','Mail'],
parseStringify = () => JSON.parse( JSON.stringify( runers, timeTableKeys ) ),
manualNewObject  = () => runers.map(o => ({ 'State':o.State,'Name':o.Name,'NR':o.NR,'Place':o.Place,'Time':o.Time })),
multilineMapNewObj = () => runers.map(o => { let newO = {}; timeTableKeys.forEach( key => newO[key] = o[key]); return newO; }); 

console.log('--= Start =--' );
console.log('1: parseStringify', parseStringify() );
console.log('2: manualNewObject', manualNewObject() );  
console.log('3: multilineMapNewObj', multilineMapNewObj() ); 

请:记住,我是这种思维方式的新手。 这是我尝试过的一些方法,虽然没有用,但可以转换或展平:

runers.map(o => $.extend(true,{}, timeTableKeys.map( key => (o[key] = o[key])  )));
runers.map(o => $.extend(true,{}, Object.assign({}, timeTableKeys.map( key => (o[key] = o[key]))  )));

runers.map(o => Object.assign({}, timeTableKeys.map( key => ({[key]:o[key]})  )));
runers.map(o => timeTableKeys.map( key => (o[key] = o[key])));  
runers.map(o => timeTableKeys.flatMap( key => ({[key]:o[key]}) ) );

1 个答案:

答案 0 :(得分:1)

您在无法使用的人中占了将近三分之一。

runers.map(o => Object.assign({}, timeTableKeys.map( key => ({[key]:o[key]})  )));

只需将... spread运算符添加到模板过滤器数组“ timeTableKeys”。

runers.map(o => Object.assign({}, ...timeTableKeys.map( key => ({[key]:o[key]})) ));