1

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

我想要做的是如果我在函数内给实体值“时间”或“新闻” findProps()

它应该以以下格式返回 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"
                  }]
                  }]
              }]}}}}

这可以变成扁平结构吗?

4

1 回答 1

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>
于 2012-07-09T05:28:21.387 回答