Getting CSV values from Javascript object

2019-07-26 09:16发布

I am trying to convert Javascript object to CSV and store it in to a file.. I have a demo: http://jsbin.com/atewix/8/edit

What I want to do is If I give the entity values "Time" or "News" inside function findProps(),

It should return CSV in the format:

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

or

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

with the current format it returns only individual values and that too as [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"
                  }]
                  }]
              }]}}}}

Can this be turned in to a flat structure?

1条回答
祖国的老花朵
2楼-- · 2019-07-26 09:53

That's a pretty deep structure, but this function will work with your data as-is. The fixSpace() function accounts for the discrepancy between Dec 9 and Dec_9.

Demo: http://jsfiddle.net/ThinkingStiff/r2kje/

Output:

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

Script:

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>
查看更多
登录 后发表回答