gpt4 book ai didi

javascript - 从 Javascript 对象获取 CSV 值

转载 作者:行者123 更新时间:2023-11-30 18:23:57 25 4
gpt4 key购买 nike

我正在尝试将 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"
}]
}]
}]}}}}

这可以变成平面结构吗?

最佳答案

这是一个相当深的结构,但此函数将按原样处理您的数据。 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>

关于javascript - 从 Javascript 对象获取 CSV 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11384441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com