我有以下对象
calendarLists = [
{Title: titel1, Color:blue, number:1}
{Title: titel2, Color:green, number:2}]
{Title: titel3, Color:red, number:3}
]
它有更多的属性,但为了简单起见,我只显示 3 个属性。我还有以下数组 [Title,number]
现在基于数组,我只想显示基于我的数组的对象属性。我的结果应该是
results =[{Title: titel1, , number:1},{Title: titel2, , number:2},{Title: titel3, , number:3}]
最佳答案
您可以将需要的属性映射为对象,将它们收集到单个对象并将所有对象映射到一个新数组。
var calendarLists = [
{ Title: 'titel1', Color: 'blue', number: 1 },
{ Title: 'titel2', Color: 'green', number: 2 },
{ Title: 'titel3', Color: 'red', number: 3 }
],
keys = ['Title', 'number'],
result = calendarLists.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));
console.log(result);
与 destructuring assignment 相同和 short hand properties .
var calendarLists = [
{ Title: 'titel1', Color: 'blue', number: 1 },
{ Title: 'titel2', Color: 'green', number: 2 },
{ Title: 'titel3', Color: 'red', number: 3 }
],
result = calendarLists.map(({ Title, number }) => ({ Title, number }));
console.log(result);
关于javascript - 有没有办法只显示基于数组的 json 对象中的选定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55425180/