转置JSON [英] Transposing JSON

查看:164
本文介绍了转置JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将同类JSON集合的所有属性提取到它自己的数组中。

I'd like to extract all the properties of a homogeneous JSON collection into it's own array.

例如,给定:

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中提取所有值的数组,如下所示:

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?

推荐答案

最终,你需要做一些迭代。

Ultimately, you're going to need to do some iteration.

map 函数就是你想要的:

function map(array, callback) {
    var result = [],
        i;

    for (i = 0; i < array.length; ++i) {
        result.push(callback(array[i]));
    }

    return result;
}

// ...

var values = map(dataPoints, function(item) { return item.Value; });

...或者只是使用外部库的地图功能:

...or just use an external library's map function:

  • Prototype - collect
  • jQuery.map
  • Underscore - map

这篇关于转置JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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