JS: how to read object array with dynamic properties? - javascript

backend server returns a sessions object with an array embedded, when I log it in the console, I get this:
Object {sessions: Array[3]}
sessions: Array[3]
0: Object
data: Object
id: "22"
__proto__: Object
1: Object
data: Object
id: "23"
__proto__: Object
2: Object
data: Object
id: "48"
__proto__: Object
length: 3
__proto__: Array[0]
__proto__: Object
so, there is an extra layer of objects with dynamic property names 0,1,2...
but I need to fill in a pure array of objects, like this:
[{id: "22", data: Object}, {id: "23", data: Object}, {id: "48", data: Object}]
so, I would refer to it like sessions[0].id... sessions[1].data... etc..
how should I reformat sessions to make it work as I wish?

sessions[0].id... sessions[1].data
Yes, exactly as you said. Just add the returned object (whatever name you gave it - I'll call it returnedObject below)
console.log(returnedObject.sessions[0].id);
Or to get all sessions
console.log(returnedObject.sessions);
Or in a variable
var sessions = returnedObject.sessions;
Or all ids
var sessions = returnedObject.sessions;
sessions.forEach(session => {
console.log(session.id);
});

Related

Im trying to create an array in JS and then loop through it

I have data saved in "localStorage".
Now i'd like to put that data into a JS array so that i can sort it and then output it.
//CREATE ARRAY
var localStorage_arr = [];
//LOOP THREW localStorage
Object.keys(localStorage).forEach(function(key){
//GET LOCALSTORAGE ITEM
var item = JSON.parse(localStorage.getItem(key));
//SET ARRAY KEY AND CREATE MULTIDIMENSIONAL ARRAY
localStorage_arr[key] = [];
//ADD SOME DATA
localStorage_arr[key]['art_id'] = item.art_id;
localStorage_arr[key]['art_nr'] = item.art_nr;
});
//SORT ARRAY
localStorage_arr.sort();
//CONSOLE.LOG ARRAY
console.log(localStorage_arr)
//IN LOG:
[1614851259727: Array(0), 1614849876677: Array(0), 1614849865169: Array(0), 1614849873617: Array(0), 1614849870613: Array(0)]
1614849865169: [art_id: 2110, art_nr: "01", article: "Test", balance: 362, …]
1614849870613: [art_id: 2110, art_nr: "01", article: "Test", balance: 362, …]
1614849873617: [art_id: 2110, art_nr: "01", article: "Test", balance: 362, …]
1614849876677: [art_id: 2110, art_nr: "01", article: "Test", balance: 362, …]
1614851259727: [art_id: 2110, art_nr: "01", article: "Test", balance: 380, …]
Question one: Why does it say: Array(0) ?
Later i try to loop threw my array:
//LOOP THREW localStorage_arr
localStorage_arr.forEach(function (item, index) {
//console.log(item, index);
});
//IN LOG: nothing..
Why can't i loop threw the array?
it is because of how javascript array work, see JavaScript Array
Arrays cannot use strings as element indexes (as in an associative
array) but must use integers. Setting or accessing via non-integers
using bracket notation (or dot notation) will not set or retrieve an
element from the array list itself, but will set or access a variable
associated with that array's object property collection.

How to get single value from JSON response ionic 4

My json response is
{results: {…}, jsontoken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXN1bHQiO…I4NH0.KFEl7IKFCGgf8Lh-NrnJ6_kThQcTG9mi617CQRzmMEg"}
jsontoken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXN1bHQiOnsiaWQiOjExLCJ1c2VyX2lkIjoiOUJHM1BWS3h5MVdhYXFYMyIsIm1vYmlsZSI6IjAwMCIsIg"
results:
createdDtm: "8/7/2020"
id: 11
invitecode: "123"
mobile: "000"
updatedDtm: "8/19/2020"
user_id: "9BG3PVKxy1WaaqX3"
walletBalance: "110"
__proto__: Object
__proto__: Object
How to get single value from this object. Example how i get invitecode?
I tried
console.log(results.invitecode) // result is undefined
invitecode is not under results. so you have to use
body.invitecode

Filtering in Object of Arrays in Javascript

I am trying to filter out an Object of Arrays wherein I have to filter out the 'designation' 'options' of a key.
My row Object looks like.
{id: 1, columns: Array(5)}
columns: (5) [InputDate, InputSelect, InputSelect, InputSelect, InputString]
id: 1
__proto__: Object
One of the columns Array where data is looks like this.
InputSelect
name: "designation"
options: Array(3)
0: {name: "Entry", value: "ENTRY"}
1: {name: "Mid", value: "MID"}
2: {name: "Experienced", value: "EXPERIENCE"}
length: 3
__proto__: Array(0)
Now I have to search inside the columns Arrays and filter out the options of "ENTRY" if the Arrays name property is 'designation' so as to return the updated Object having this filtered value.
What I am trying now is
row.columns.map( key => {
if (key.name === 'designation') {
key.options.filter( r => r.value === "ENTRY" )
}
But it doesn't seem to be updating the row Object.
This should solve your problem.
row.columns.filter(x=>x.name=="designation").map(i=>i.options.filter(z=>z.name==="Entry"));

Looping through an array of objects and mapping each object them to a single template object

I have a two sets of data, one formatted like so:
title: "Test Json",
showProgressBar: "top",
showQuestionNumbers: "off",
pages: [
{
questions: [
{
type: "",
name: "",
title: "",
hasOther: true,
isRequired: true,
colCount: 4,
choices: []
}
]
}
]
};
The other formatted like so:
{Answers: "“18-24”, “25-50”, “50+”",
​
Question: "How old are you?",
​
QuestionNumber: "1",
​
isRequired: "TRUE",
​
type: "radiogroup"}
This second set of data is multiple of these objects, which I am looping through using a forEach loop like so:
data.forEach((data, i)=>{
console.log(data)
// returns above object x3
})
What I want to do is use the first object and map values to the questions array using the values of the second object, so for example questions[0].type would be mapped to data.type.
I have managed to figure out mapping one object to the template doing this:
data.forEach((data, i)=>{
console.log(data)
questions[0].type = data.type
questions[0].name = data.Question
questions[0].title = data.Question
questions[0].choices = [data.Answers]
})
But this only maps the first object in the data array of objects, and I want to basically create a new template object based on the number of objects in the data array and create as many 'filled questions templates' as there is objects in data array
Any pointers and help would be lovely <3
Try this
data.forEach((data, i)=>{
console.log(data)
questions.push([{
type: data.type
name: data.Question
title: data.Question
choices: [data.Answers]
}])
})
Updated this answer with your additional question

Combine 2 different javascript json objects into one with a loop and joining on the questionid ,

So I am trying to combine 2 different javascript object than I can end up using in an angularjs ng-repeat . since there is a 1 to many relationship from the database, I was pulling queries separately.
What I have is this:
Main list of data , 3 object sample
0: Object
$$hashKey: "object:4"
Active:true
QuestionId:2
SalesChannel:"DTD"
1: Object
$$hashKey: "object:5"
Active:true
QuestionId:3
SalesChannel:"DTD"
2: Object
$$hashKey: "object:6"
Active:true
QuestionId:5
SalesChannel:"DTD"
Then another query returned data into what I want to relate as JSON into the other object
Object { Id: 3, Name: "Text box" QuestionId: 3}
{ Id: 4, Name: "Text box" QuestionId: 3}
{ Id: 9, Name: "Text box" QuestionId: 5}
So since I have both of these objects , I am wanting to combine.
Naturally I would think that I should return from the database, but then I also think about looping over and appending
for loop on main
{
.... find where main.QuestionId = sub.QuestionId and it to be added in as a nested object of json type...
Thus the end result SHOULD look like
[{
Active:true,
QuestionId: 3
SubData: [ {
Id: 3,
Name: "TextBox
QuestionId:3
},
{
Id: 4,
Name: "TextBox
QuestionId:3
}],
SalesChannel: "DTD"
}]
// and so on
How can i achieve this?
You want to go through all of the main objects, and assign to them only those results from second query. Use Array.prototype.forEach to go through them all, and Array.prototype.filter to select only appropriate results from secondary query.
firstQueryResult.forEach((firstObject)=>
firstObject.subdata = secondQueryResult.filter((secondObject)=>
secondObject.QuestionId === firstObject.QuestionId))
BTW, this has nothing to do with angularjs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Categories

Resources