如何使用 underscore.js 产生扁平化结果
json 对象是
var data = [{"Parent":1,"Child":[4,5,6]},{"Parent":2},{"Parent":3}]
如何使用 underscore.js chain/map/pluck 等...函数来获得展平结果
var result = [];
for (var i = 0; i < data.length; i++) {
result.push(data[i].Parent);
if (data.Child != undefined) {
for (var j = 0; j < data[i].Child.length; j++) {
result.push(data[i].Child[j]);
}
}
}
console.log(result) >> //1,4,5,6,2,3
The json object is
var data = [{"Parent":1,"Child":[4,5,6]},{"Parent":2},{"Parent":3}]
How can I use underscore.js chain/map/pluck etc... function to get the flatten result
var result = [];
for (var i = 0; i < data.length; i++) {
result.push(data[i].Parent);
if (data.Child != undefined) {
for (var j = 0; j < data[i].Child.length; j++) {
result.push(data[i].Child[j]);
}
}
}
console.log(result) >> //1,4,5,6,2,3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个更短的解决方案:
Here's a shorter solution:
或者,如果您想要一个可以普遍展平任何对象或数组集合的函数,
您可以使用以下方式扩展 Underscore:
Crush(由于缺乏更好的名称)可以像
_.crush 一样调用(list, [shallow])
或_(list).crush([shallow])
,其行为与 Underscore 内置 Flatten 的通用形式完全相同。它可以传递任意深度的嵌套对象、数组或两者的集合,并将返回一个包含所有输入值和自己的属性的单级数组。与Flatten类似,如果向其传递一个计算结果为true的附加参数,则执行“浅”执行,输出仅扁平化一级。
示例1:
示例2:
代码本身的解释如下:
希望对需要的人有所帮助。 :)
Alternatively, if you want a function that can universally flatten any collection of objects or arrays,
You could extend Underscore with:
Crush (for lack of a better name) can be called like
_.crush(list, [shallow])
or_(list).crush([shallow])
and behaves exactly like a generalized form of Underscore's built-in Flatten.It can be passed a collection of nested objects, arrays, or both of any depth and will return a single-leveled array containing all of the input's values and own properties. Like Flatten, if it is passed an additional argument which evaluates to true, a "shallow" execution is performed with the output only flattened one level.
Example 1:
Example 2:
An explanation of the code itself is as follows:
Hope it helps if anyone needs it. :)
假设您想先获取父母,然后获取孩子:
Assuming you want to first get the parents and then get the children:
如果您想使用 underScore.js 将多个数组组成的数组展平为一个元素数组,那么您就可以这样做。按照我的例子:
我的图表有 2 个系列。每个系列都有一个名称和一系列数据点 {xtime, yValue}。我的目标是将两个系列中的所有数据点整理为一系列数据点,以便填写表格。
我的结果:
If you want to use underScore.js to flatten an array of many arrays into one array of elements, that's how you do it. Follow my example:
My graph has 2 series. Each series has a name and a sequence of datapoints {xtime, yValue}. My goal is to iron out all the data points from 2 series into one series of data points so to fill out a table.
My result :