JavaScript ES6-仅采用嵌套JSON数组的某些键/部分的简便方法? [英] JavaScript ES6 - Concise way to take only certain keys/parts of a nested JSON array?

查看:38
本文介绍了JavaScript ES6-仅采用嵌套JSON数组的某些键/部分的简便方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以我的应用程序状态存储的JSON数据数组.它包含详细页面所需的属性(大约10个不同的字段).

I've got a JSON array of data that is stored in my app's state. It includes attributes that a detailed page would need (around 10 different fields).

我的列表视图只需要其中两个.例如:

My list view only needs two of those. For example,:

[
  {
    "id": 1,
    "title": 'Derp',
    "subtitle: 'Derp',
    "another": 'Derp,
    //... more attributes
  },
  {
    "id": 2,
    // ... etc
  }
]

我的列表视图仅与ID,标题和字幕有关.仅使用我指定的键来获取相同数据的最简洁方法是什么?

My list view is only concerned with the id, title, and subtitle. What's the most concise way to obtain the same data, but only with the keys that I specify?

我应该使用地图吗?还是破坏性的?

Should I be using map? Or destructuring?

非常感谢警察的答复,尽管他们做出了努力.这极大地帮助了我,我确实尝试了一段时间以弄清楚该如何做.我来自Ruby,所以ES6不是我的强项.

Much thanks for the answers despite the effort police showing up. This helped me greatly and I did try for a while to figure out how to do this. I'm coming from Ruby so ES6 is not my forte.

用例是仅从包含所有数据属性的全局Redux存储中返回React组件所需的内容.例如,我的列表视图仅需要JSON数据中的2/3属性.我正在使用redux 选择器来做到这一点.

The use case is to only return what a React component needs from a global Redux store that contains all data attributes. For instance, my list view only needs 2/3 attributes from the JSON data. I'm using redux selectors to do this.

第二/后一个问题:这种方法有什么名称,您只使用JSON的一部分?我想制作一个在redux选择器中执行此操作的方法,并且需要提供一个名称.我想将其称为化简器,但由于在Redux领域中已使用化简器"一词来修改状态,因此无法正常工作.

2nd/post question: Is there any name for this type of method, where you only take parts of JSON? I want to make a method that does this in a redux selector, and I need to come up with a name. I wanna call it a reducer but that doesn't quite work as the term reducer is already used in the Redux world for methods that modify state.

推荐答案

您可以使用解构和重构的对象映射值.

You could map the values with a deconstructed and reconstructed object.

解构分配:

解构赋值语法是一种JavaScript表达式,可以将数组中的值或对象中的属性解压缩为不同的变量.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

var a, b;
({a, b} = {a: 10, b: 20});
console.log(a); // 10
console.log(b); // 20

简写属性名称

var a = 'foo', b = 42, c = {};
var o = {a, b, c};

var data = [{ id: 1, title: 'Derp', subtitle: 'Derp', another: 'Derp', bla: 42 }, { id: 2, title: 'Derp', subtitle: 'Derp', another: 'Derp', bla: 42 }],
    short = data.map(({ id, title, subtitle }) => ({ id, title, subtitle }));

console.log(short);

这篇关于JavaScript ES6-仅采用嵌套JSON数组的某些键/部分的简便方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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