有没有一种方法只能显示基于数组的json对象中的所选属性 [英] Is there a way to only show selected property in a json object based on a array

查看:32
本文介绍了有没有一种方法只能显示基于数组的json对象中的所选属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象

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); 

解构分配相同简短属性.

 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); 

I have the following object

calendarLists = [
    {Title: titel1, Color:blue, number:1}
    {Title: titel2, Color:green, number:2}]
    {Title: titel3, Color:red, number:3}
]

It has alot more property but for simplicity sake ill just show 3 properties. I also have the follow array [Title,number]

Now basing from the array I only want to show object property based on my array. My results should be

results =[{Title: titel1, , number:1},{Title: titel2, , number:2},{Title: titel3, , number:3}]

解决方案

You could map the wanted properties as objects, collect them to a single object and mapp all objects for a new array.

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);

The same with a destructuring assignment and 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);

这篇关于有没有一种方法只能显示基于数组的json对象中的所选属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆