This question already has answers here:
JavaScript: How to iterate object with two the same keys (and get two values)
(2 answers)
Closed 5 years ago.
I found a JSON file with containing historical events on this website here:
The structure of the file is as follows:
{ result:
{
count: "37859",
event: {},
event: {},
...
event: {}
}
}
As you can see, every objects containing data about a particular event is stored within its own object but all of them have the same key, "event". Because of this the result of the d3.json() method is only the last "event" object. How can I get an array of all of these "event" objects?
Sorry if I'm using the word "object" in a wrong way, they are represented as objects in the browser console and I don't know how else to describe them as in english.
The file they're providing to you is not valid JSON so I can't see any way of using d3.json() and getting it to work.
I think you have two options here:
Speak to the provider and get them to format the file properly.
Load the file as text instead of JSON, use string.replace to reformat the structure to be an array of events, rather than a collection of fields called event on that object.
Something like this:
{
result:
{
count: "37859",
events: [
{ ...event1... },
{ ...event2... },
{ ...event3... }
]
}
}
An easier option might be to replace each occurrence of the string "event" with a unique version like "event-1", "event-2".
Related
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 months ago.
I have a script which receives a JSON formatted file as input and allows the user to call out a JSON object name for specific processing. I loop through the JSON file using a foreach() to process the specific items requested by the end user.
In this example The JSON input file has an object array called "socks". The requested JSON object name could be input by the user as "socks" as this would be the object they would like to have the code perform a function on.
I push all of these "socks" to a new array to perform the work on.
//working code
jsonDataIn.socks.forEach(function(s) {
newArray.push({ socks:s })
});
The above code functions as needed because I have hardcoded the array name as 'socks'. I cannot figure out how to assign the array name as a variable to apply the users input.
//I'd tried assigning just the array name as a variable, as well as both the data and array and those both are not valid.
let inputValueFromUser = 'socks';
let arrayNameVar=jsonDataIn.inputValueFromUser;
arrayNameVar.forEach(function(s) {
newArray.push({ [inputValueFromUser]:s })
});
nor this
let inputValueFromUser = 'socks';
let arrayNameVar=inputValueFromUser;
jsonDataIn.arrayNameVar.forEach(function(s) {
newArray.push({ [inputValueFromUser]:s })
});
In the above code the [inputValueFromUser] works for assigning the value to the newArray, but I cannot figure out how to get it to work inline as a form of 'jsonDataIn.inputValueFromUser.forEach()'. I found many examples if I were using multiple arrays in a forEach loop, but not how to pass the 'inputValueFromUser' as an array name.
I know it has to be a simple solution that I'm missing. Any assistance is appreciated.
All of the failed code that I've tried to make work has resulted in "TypeError: Cannot read properties of undefined (reading 'forEach')"
This question already has answers here:
How to get all properties values of a JavaScript Object (without knowing the keys)?
(25 answers)
Closed 1 year ago.
{
pet: {
"0.628": 92694.5,
"8739.836": 96391.94
},
try: {
//same
}
}
When I specify the key, I get the values but i am trying to read all the values without knowing the keys. I have even tried regex, but nothing seems to be working. As you can see i am fairly new. So sorry if this was a stupid question.
console.log(data.pet) // Gives [Object Object]
console.log(data.pet["0.628"])//Gives the value
console.log(data.pet[0])//Gives undefined
I don't see in what context you'd want to access a json object without knowing the keys.
but what you can do is to parse the json file into a javascript object, and call Object.keys() to get the keys of that object
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I was trying to get data from the notes array in the data object. I'm getting the object from mongodb and I want to get the array called notes. but I can't do it. for some reason. In java there is like Object.get(notes) and I can get a specific field within the object but I don't know how to do that in js. And I haven't been able to find something that works elsewhere online.
here is my code
axios.post('/api/user/notes')
.then(res => {
console.log( Object.values(res.data));
dataSet = Object.values(res.data);
console.log(dataSet[0]);
console.log(dataSet.notes[0]);
}).catch(err => {
console.log('it didnt work' + err);
});
image
dataSet is an array. So, to get the notes, you have to first select the first element of data, dataSet[0] and then the notes array. To get the first note, it would be dataSet[0].notes[0]. Also, beware that you are setting a global variable (perhaps on a browser's window object) when you type dataSet = ... What you probably want is to declare a variable local to the function with var dataSet = ...
This question already has answers here:
How to serialize a raw json field?
(2 answers)
Closed 5 years ago.
I am creating a javascript object from a c# object and one of the properties is a reference to a js function , but when serializing the object the value has quotes around it witch makes it a normal string and not a function.
this is the current output :
{ "x": "functionNameToBeCalled" }
But I need it to be like
{ "x": functionNameToBeCalled }
Is there anyway to do this with Json.Net or do I have to create the js object manually?
I tried using the JsonPropertyAttribute but can't figure out which property to set!!!
change the way of calling your method, something like this:
window.z= function(){ console.log('hi');}
var b = { a: 'z'}
window[b.a]();
so no need to change json serialization behavior.
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Access Javascript nested objects safely
(14 answers)
Test for existence of nested JavaScript object key
(64 answers)
Closed 5 years ago.
I'm using v4 sheets API from google-api-nodejs-client, it returns a lot of data. Though I filter it using fields arguments, the structure of JSON is very complex. So to incorporate it into my logic, I flatten it. And it needs to be safe, I don't want any exceptions to be thrown.
This is how the UNSAFE version of the code looks:
const data = response.sheets[0].data;
const columns = data.map((column) => {
const rowData = column.rowData;
const values = rowData[0].values;
return rowData.map((cellData) => cellData.values[0].userEnteredValue);
});
// ...
If JSON is invalid, an exception is inevitable. I don't want this. The problem is that to fix it, I should add plenty of if-s. This would make the code look ugly.
Let's summarize: Is there a way to map JSON into local objects safely and expressive (and preferably relying only on features of ES6)?
UPDATE
Let's add a little more context. This is a small insight how deep the JSON is, and all I need to map it to an array of strings ('1.06' is one of them).
{
"sheets":[
{
"data":[
{
"rowData":[
{
"values":[
{
"userEnteredValue":{
"stringValue":"1.06"
}
}
]
},
...