Better mapping JSON to objects in JavaScript [duplicate] - javascript

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"
}
}
]
},
...

Related

How to get array out of object in JS [duplicate]

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 = ...

How to access a particular path/adress inside an object? [duplicate]

This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));

Is Object and Array in Javascript the same thing? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Are Javascript arrays primitives? Strings? Objects?
(7 answers)
Closed 2 years ago.
I'm looking for an elegant way of understanding JavaScript array and objects.
I came to an anomaly in which I got stuck.
Since in PHP or other languages, when we make an array e.g
$a = [
admin => 1,
staff => 2
];
so if we want to access its element we can do so by for e.g $a[admin] and we will get 1.
similarly if its an object e.g
$a = (object) [];
$a->sadd = 'sas';
we can access it with arrow
$a->sadd
and if we try to access object elements in the style of array i.e like this $a['sadd'] it will throw error that you can not use it as array style.
But I was surprised by the anomaly in JavaScript.
I have observed that in JavaScript no matter what I am making, an array or object, the elements of both can be accessed via dot or via array style and i found no difference in there accessing style.
for e.g
var a = {sadd : 1}
I can access its element via a['sadd'] or a.sadd both will give 1
So I am confused by this anomaly and wondering whether array and object both datatypes are considered same in JavaScript?
An array is indeed an object.
Javascript is a dynamic language and accepts mixed types of entities. Also while accessing, dot notation seems to be more clearer (atleast imo) and is preferred. Bracket notation is used for dyanamic keys.
The difference between array and objects boils down to their usecase:
Array -> Contiguous block of memory
Object -> key-value pair (like a dictionary)
Your php example is actually creating what we'd call an object in JS, not an array. In JS an array is a list of items, which you can find items by array[i], or by looping.
An object is a collection of fields, which you can go into by object.fieldName or object[fieldName].
This can be confusing in JS though, because theoretically everything is an "object", including arrays, due to the way things are handled lower down..
I would recommend following along with the https://justjavascript.com/ course for good mental models on how objects work in JS.

Javascript/Typescript array.map function is changing the value of a variable defined before the .map [duplicate]

This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 8 months ago.
I am playing around with some react code, and observed unexpected (to me) behaviour. Can someone please explain whats going on?
export default function AnswerBox(props: any) {
const before = props.answers;
console.log('const before ', before);
props.answers.map((value: any) => {value.selected = 'asdfasdfasdf'})
console.log('answer props after' , props.answers);
Both of the log lines show an array of objects with 'selected':'asdfasdfasdf'
Is there some tricky async business I'm missing here? Thanks in advance.
For objects and arrays containing other objects or arrays, copying these objects requires a deep copy. Otherwise, changes made to the nested references will change the data nested in the original object or array , here the code :
const before=JSON.parse(JSON.stringify(props.answers));
If you have complex object, with Dates, functions, undefined, Infinity, [NaN], RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays.
I would suggest usin.

Using JSON data with identical keys (in D3) [duplicate]

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".

Categories