转置 JSON
我想将同构 JSON 集合的所有属性提取到它自己的数组中。
例如,给定:
var dataPoints = [
{
"Year": 2005,
"Value": 100
},
{
"Year": 2006,
"Value": 97
},
{
"Year": 2007,
"Value": 84
},
{
"Year": 2008,
"Value": 102
},
{
"Year": 2009,
"Value": 88
},
{
"Year": 2010,
"Value": 117
},
{
"Year": 2011,
"Value": 104
}
];
我想从 dataPoints 中提取所有值的数组,看起来像:
var values = [100, 97, 84, 102, 88, 117, 104];
是否有一种干净/有效的方法来完成这种转置,而不是手动迭代和构造?
I'd like to extract all the properties of a homogeneous JSON collection into it's own array.
For example, given:
var dataPoints = [
{
"Year": 2005,
"Value": 100
},
{
"Year": 2006,
"Value": 97
},
{
"Year": 2007,
"Value": 84
},
{
"Year": 2008,
"Value": 102
},
{
"Year": 2009,
"Value": 88
},
{
"Year": 2010,
"Value": 117
},
{
"Year": 2011,
"Value": 104
}
];
I'd like to extract an array of all Values from dataPoints that looks something like:
var values = [100, 97, 84, 102, 88, 117, 104];
Instead of iterating and constructing manually, is there a clean/efficient way to accomplish this kind of transposition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最终,您将需要进行一些迭代。
map
函数就是您想要的:...或者仅使用外部库的映射函数:
Ultimately, you're going to need to do some iteration.
A
map
function is what you want here:...or just use an external library's map function:
您可以通过创建自己的地图功能来做一些有趣的事情你需要用它做什么......但在一天结束时,你最终将迭代原始数组并取出你感兴趣的值
只是为了好玩,给定这个方法:
你可以轻松获得一个数组看起来像你所描述的:
you can probably do some interesting things by creating your own map function depending on what you need to do with it ... but at the end of the day, you will end up iterating the original array and pulling out the value you are interested in
Just for fun, given this method:
You can easily get an array that looks like what you're describing:
我同意 Joel 的观点,即这里没有魔法 - 您需要迭代数组才能提取值。迭代数组的最快方法是简单的 for 循环。请参阅此处了解有关数组的好文章迭代性能。归根结底,即使对于非常大的数组,如果编码正确,这也不应该是一个非常昂贵的操作。
我要为您补充的一件事是您是否有机会在创建数据时更改数据的结构。例如:如果您有一个创建此数据的循环,您是否可以在创建年份“对象”数组的同时创建一个“值”数组?
I agree with Joel that there's no magic here - you will need to iterate over the array in order to extract the values. The fastest way to iterate over an array is a simple for loop. See here for a good post about array iteration performance. End of the day, even for a very large array, this should not be a very expensive operation if you code it correctly.
One thing I would add for you think about is whether you have the opportunity to change the structure of the data as it's being created. eg: if you have a loop that creates this data, could you also create an array of 'values' at the same time as you create an array of year 'objects'?