let test = [];
d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' data.branch_nm '</div>';
test.push(obj);
}
});
console.log(test);
console.log("test[0] : " test[0]);
console.log("test.length : " test.length);
[enter image description here][1]
I made the csv file into an object array.
And as a result of outputting the array, the array was output well,
enter image description here
but when outputting index 0, undefined came out and the length of the array was also 0.
It was printed properly when it was printed from the console.
What's the problem?
CodePudding user response:
Without a jsfiddle or sandbox to play with, I can't tell exactly what is going on, but what I believe is happening is a mix of two things:
d3.csv
is an async function, and therefore returns a promise.- The function you pass on to
d3.csv
is supposed to tell the function how to parse every element in the csv, and should return the parsed object, not add it to an external array or anything like that. Every element you return in that function will be an element in your resulting array
There's (at least) two possible ways you can deal with this:
await
the async function, and its return value will be your required value, something like
const test = await d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' data.branch_nm '</div>';
return obj;
}
});
console.log(test);
console.log("test[0] : " test[0]);
console.log("test.length : " test.length);
Notice that here the function you pass onto d3.csv
returns the object in the way you want to format it!
- Do your logic in a
.then
statement, which also waits for the promise to be fulfilled:
d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' data.branch_nm '</div>';
return obj;
}
}).then((test) => {
console.log(test);
console.log("test[0] : " test[0]);
console.log("test.length : " test.length);
});