从Javascript对象获取CSV值

时间:2012-07-08 15:47:22

标签: javascript arrays json recursion hash

我正在尝试将Javascript对象转换为CSV并将其存储到文件中。 我有一个演示:http://jsbin.com/atewix/8/edit

我想要做的是如果我在函数findProps()中给出实体值“Time”或“News”,

它应该以以下格式返回CSV:

"http://www.testingmyurl.com", Time, Dec 9, 2012

"http://www.testingmyurl.com",News, Germany,Election
"http://www.testingmyurl.com",News,Egypt, Revolution

使用当前格式,它仅返回单个值,而且也返回[object,object]

{
"_index": "test",
"_source": {
     "link": "http://www.testingmyurl.com",
  "Categories": {
      "Types": {
          "Events": [{
              "count": 1,
              "entity": "Time",
              "Time": [{
                  "entity": "Dec 9",
                  "Dec_9": [{
                      "count": 1,
                      "entity": "2012"
                  }]
                  }]
              }]}}}}

可以将其转换为扁平结构吗?

1 个答案:

答案 0 :(得分:2)

这是一个非常深入的结构,但此功能将按原样处理您的数据。 fixSpace()函数说明了Dec 9Dec_9之间的差异。

演示: http://jsfiddle.net/ThinkingStiff/r2kje/

输出:

News:
"http://www.testingmyurl.com","News","Germany","Election"
"http://www.testingmyurl.com","News","Egypt","Revolution"
Time:
"http://www.testingmyurl.com","Time","Dec 9","2012"

脚本:

function findProps( name, data ) {
    var results = [],
        events = data._source.Categories.Types.Events,
        link = data._source.link;

    for( var eventIndex = 0; eventIndex < events.length; eventIndex++ ) {
        var event = events[eventIndex];
        if( event.entity == name && event[name]  ) {
            for( var entityIndex = 0; entityIndex < event[name].length; entityIndex++ ) {
                var entity = event[name][entityIndex],
                    entityName = fixSpace( entity.entity );
                if( entity[entityName] ) {
                    for( var valueIndex = 0; valueIndex < entity[entityName].length; valueIndex++ ) {
                        var value = entity[entityName][valueIndex];
                        results.push( 
                              '"' + link + '",'
                            + '"' + name + '",'
                            + '"' + entity.entity + '",' //un-fixSpaced name
                            + '"' + value.entity + '"'
                        );
                    };
                };
            };
        };
    };

    return results;
};

function fixSpace( value ) {
    return value.replace( ' ', '_' );        
};

var news = findProps( "News", data );
document.getElementById( 'news' ).innerHTML = news.join( '<br />' );
var times = findProps( "Time", data );
document.getElementById( 'time' ).innerHTML = times.join( '<br />' );

HTML:

News:
<div id="news"></div>
Time:
<div id="time"></div>