How to create JSON format dictionary? - javascript

I would like to format my data with a key to access the information. This is what I currently have:
const dict = [];
dict.push({"student": "Brian", "id":"01", "grade":"Sophomore"})
return dict;
Output:
{
"student":"Brian"
"id": "01",
"grade": "Sophomore"
}
However, I am interested in creating this type of format with my data:
{
"student":"Brian" [
{
"id":"01",
"grade": "Sophomore"
}
]
}
How would I be able to do so? I would like to use "student" as my key to access the rest of its information associated.

You're basically there. However objects always need keys to go along with the values, so you need to assign a key to the object you want to create
const dict = [];
dict.push({
"Brian": {
"id": "01",
"grade": "Sophomore"
}
})
// to retrieve:
let brian = dict.filter(e=>Object.keys(e)[0]==="Brian").flatMap(Object.values)
if (brian && brian.length>0) console.log(brian[0])
//You could also set up your `dict` like this:
const dict2 = {};
dict2["Brian"] = {
"id": "01",
"grade": "Sophomore"
};
//and that would allow you to retrieve your object with
brian = dict2.Brian;
console.log(brian)

Related

How to Turn a Multiple Array Object into Query String Parameters in JavaScript

I have the following object below with multiple arrays.
{
"services": [
{
"id": "100",
"name": "PIX"
},
{
"id": "200",
"name": "Rendimentos"
}
],
"channels": [
{
"id": "300",
"name": "Chat"
}
]
}
The idea is to generate query strings, something like that.
services=100&services=200&channels=300
I know you can do it with map and join, but I would know if it was with a pure object, now this format below, I'm confused
You can use URLSearchParams() API.
Iterate your data and append key/value pairs or map an entries array to pass to the constructor
I have no idea what determines the expected output you have shown from the data displayed so am using a simpler data structure for demonstration purposes.
You can combine with URL() API to create full url string as shown below also
const data = [
{name:'foo', value:10},
{name:'bar', value:20}
]
// Loop and append key/values
const params = new URLSearchParams();
data.forEach(e => params.append(e.name, e.value));
console.log('params:', params.toString());
// Alternate approach passing entries array to constructor
const params2 = new URLSearchParams(data.map(e => [e.name,e.value]));
console.log('params2:',params2.toString())
//Adding to a URL
const url = new URL('http://example.com')
url.search = params
console.log('Full url:',url)
Using the updated array data in question:
const data={services:[{id:"100",name:"PIX"},{id:"200",name:"Rendimentos"}],channels:[{id:"300",name:"Chat"}]};
const entries = [];
Object.entries(data).forEach(([k,arr])=> arr.forEach(({id}) => entries.push([k,id])));
const params = new URLSearchParams(entries);
const url = new URL('http://example.com')
url.search = params;
console.log(url)
Looks like you're hung up on trying to iterate an object with map() or join(), which you can't do directly. Instead you can use Object.entries to convert the object into an array and iterate that. Since there is a nested map() you can flat() it before join()
let obj = {
"services": [{
"id": "100",
"name": "PIX"
},
{
"id": "200",
"name": "Rendimentos"
}
],
"channels": [{
"id": "300",
"name": "Chat"
}]
}
let queryString = Object.entries(obj).map(s => s[1].map(e => `${s[0]}=${e.id}`)).flat().join('&')
console.log(queryString)

How to convert JSON string having multiple rows to single row using javascript function

I have an output of REST API in following JSON format:
I need to convert the format to flat format so it can be passed as input to another API call.
{
"result": {
"data": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
},
// ... 1000's of rows like this
]
}
}
I need to convert it in below format using a java-script
Desired format:
{"result":{ "data":[{"id":"b3","dateTime":"2019-09- 10T11:32:05.220Z","DiagnosticAccelerationSideToSideId":0,"DiagnosticAccelerationForwardBrakingId ":2.824315071105957},...
The rows needs to be merged with primary key as combination of ID and dateTime attributes. Please note the diagnostic id value becomes key for the required format and data value is the value of the key.
Is there any way to convert this JSON to above flat format.
Need to convert JSON having many rows for single data entry to single row format. Need one java-script function that can accept a string of rows format and convert or merge it and return the string in desired format
function String mergeRows(String flatDataJSONString) {
...
}
If the items are ordered (meaning i and i+1 are merged) than iterate with jumps of i += 2;
If its not ordered or the amount of items to be merged can be > 2 you use an object with unique key composed of the id and date, and override its data whenever a record match this key:
function merger (jsonStr) {
// convert str to obj
const jsonObj = JSON.parse(jsonStr);
const dataObj = {};
for (let i = 0; i < jsonObj.result.length; i++) {
const item = jsonObj.result[i];
// use unique key to merge by
const itemUniqueKey = item.device.id + item.dateTime;
// take last value or create empty object if not exists
const existingItem = dataObj[itemUniqueKey] || {};
// add some logic to merge item with existingItem as you need
...
// set the result back to dataObj to be used on next merges
dataObj[itemUniqueKey] = [merge result of item and existing item];
}
// take dataObj values, you don't need the keys any more
const dataArr = Object.values(dataObj);
const finalResult = {
result: {
data: dataArr
}
}
// convert back to json
return JSON.stringify(finalResult);
}
As stated in the comment you want first to have a clean json definition in order to stringify it. Please get to the following definition of your JSON first:
const json = {
"result": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
}]
};
and then you will be able to perform like hereafter :
JSON.stringify(json)
Hope this helps !

Access object inside the array which is inside the other object

I have an array of objects, where inside each object I have another array. I need to access the object inside that array. How do I do that?
As an example, here is my function where I log into the console each one of those arrays. And I want to console log each description instead.
const var = data.filter((u) => {
console.log(u.array)
})
And here is the JSON data
[
{
"agreed": true,
"email": "test#test.com"
"array": [
{
"name": "Alex",
"city": "Pedro",
"state": "WA",
"description": "Alex was very patient. He is one of the good guys!"
}
]
}
]
Here is the code snippet. data contains the original array then u contains each object of outer array. Then u.array.map traverses each individual array and i.description contains each sub-array's description.
data.map((u) => {
u.array.map((i) => {
console.log(i.description);
}
})
if you know the exact index, you can do this.
const var = data.filter((u) => {
console.log(u.array[0].description)
})
if you dont know the exact index, or if you wanna do this for each item in the array you can do this.
const var = data.filter((u) => {
u.array.forEach(item => {
console.log(item.description)
})
})
Well,
if this would be the structure of your Javascript Object
var data =
[
{
"agreed": true,
"email": "test#test.com"
"array": [
{
"name": "Alex",
"city": "Pedro",
"state": "WA",
"description": "Alex was very patient. He is one of the good guys!"
}
]
}
]
Then You can access the array by,
data[0].array[0].name;
And you can console.log description like this, if you are using jquery
$.each(data[0].array, function(i,v){
console.log(v.description);
})
You index into arrays with array[someIndex] starting with 0 for the first item.
So you can:
let arr = [{
"agreed": true,
"email": "test#test.com",
"array": [{
"name": "Alex",
"city": "Pedro",
"state": "WA",
"description": "Alex was very patient. He is one of the good guys!"
}]
}]
// get the first whole object
console.log(arr[0])
// get the arra property of the first object
console.log(arr[0].array)
// get the first object of that array
console.log(arr[0].array[0])
// get a property on that object
console.log(arr[0].array[0].name)
If you need to dig into an array and access of manipulate values, you can use tools like forEach, reduce(), etc. to loop over them:
let arr = [{"agreed": true,"email": "test#test.com","array": [{"name": "Alex","city": "Pedro","state": "WA","description": "Alex was very patient. He is one of the good guys!"},{"name": "Mark","city": "Anchorage","state": "AK","description": "Mark is also patient. He is one of the good guys!"}]},{"agreed": true,"email": "test#test.com","array": [{"name": "Steve","city": "New York","state": "NY","description": "Steve was very patient. He is one of the good guys!"},{"name": "Nancy","city": "Anchorage","state": "AK","description": "Nancy is also patient. She is awesome!"}]}]
// log each name
arr.forEach(obj => {
obj.array.forEach(item => {
console.log(item.name)
})
})
// build a new list of just the cities
let cities = arr.reduce((arr, obj) => {
obj.array.forEach(item => {
arr.push(item.city)
})
return arr
}, [])
console.log(cities)
You can save all descriptions to an array or just display it, like this
let descriptions = [];
data.map(item => item.array)
.forEach(array => {
array.forEach(obj => {
console.log(obj.description);
descriptions.push(obj.description);
});
});
console.log(descriptions);

Javascript using variable as key to get nested object value

Assume I have the following object:
var jsonObj = {
"response":{
"result":{
"status":{
"name": "Eric"
}
}
}
}
And now i'd like to dynamically access a nested property:
jsonKey = "response.result.status.name";
console.log("the status is: " + jsonObj.jsonKey); //I cannot call jsonObj.jsonKey here
Is there any way to achieve this?
You cannot access a deeply nested property as simple as you expect. Instead you need to use the obj[propertyNameAsString] syntax to dive deeper into the response one by one.
This would be one way of getting there:
let response = {
"response": {
"method": "GetStatus",
"module": "Module",
"data": null,
"result": {
"status": {
"name": "Eric"
},
"id": 1
},
"result_code": {
"error_code": 0
}
}
}
let keyString = "response.result.status.name"
let keyArray = keyString.split('.'); // [ "response", "result", "status", "name" ]
var result = response;
for (key of keyArray) {
result = result[key]
}
console.log(result)
Please be aware that this is not failsafe against cases where one of those strings in keyArray does not exist as a property on the preceding object.
You can do like this something['bar']
Where bar is your variable that has been converted to string, in our case:
jsonObj[`${jsonKey}`]

Loop over JSON items whether JSON object has multiple arrays or not

I have a working version of a function to loop through a single array in a JSON object, e.g.
[{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}]
sample function:
function FindName(NameToFind, data1) {
objData = JSON.parse(data1);
for (var i = 0; i < objData.length; i++) {
var Name = objData[i].Name;
if (Name == NameToFind) {
alert("found!");
}
}
}
Now I need to change this function to allow for either single OR multiple arrays e.g.
{
"Table1": [{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}],
"Table2": [{
"Name": "Sarah",
"Surname": "Parker"
},
{
"Name": "Jonah",
"Surname": "Hill"
}
]
}
Is there a way to determine whether the object has 1 array (like in first example) or more than one arrays (like in 2nd example), and any advice/guidance on how to extend the function to be able to loop through all the items whether it has 1 array or multiple arrays?
Your first object is an array, the second one isn't.
You can test if your argument is an array, or even just test
if (objData[0]) // that's an array
EDIT :
if you want to iterate over all properties of a (just json decoded) object, when it's not an array, you can do this :
for (var key in objData) {
var value = objData[key];
// now use the key and the value
// for example key = "Table1"
// and value = [{"Name":"John","Surname":"Johnson"}, ... ]
}

Categories

Resources