How to write dynamic json object inside an array in javascript - javascript

Desired output--
[
{
"group1": {
"Token1": "123443423",
"Token2": "121414141"
},
"group2": {
"Token1": "123443423",
"Token2": "121414141"
}
}
]
Group1 and group2 is dynamic and also the token1 and token2 value is dynamic. So i write this way --
[ {`${group1}`:{
"Token1" : `${token1}`,
"Token2" : `${token2}`
},
`${group2}`:{
"Token1" : `${token1}`,
"Token2" : `${token2}`
}
}]
But ${group1} shows error unexpected token ` (template literate).

1. [Specific]
// helper function
function createGroup(groupName, token1, token2) {
const group = {};
group[groupName] = {
Token1: token1,
Token2: token2
};
return group;
}
//and then create a result output
var result = [
createGroup('group1', group1token1, group1token2),
createGroup('group2', group2token1, group2token2),
]
2. [More general] For multiple paramenters (more than fixed 2):
your parametersObject have to be as:
{
Token1: 'token_1_value_here',
Token2: 'token_2_value_here',
...
ParameterN: 'parameter_n_value_here',
...
}
And then:
// helper function 2
function createGroup(groupName, parametersObject) {
const group = {};
group[groupName] = parametersObject;
return group;
}
//and then create a result output
var result = [
createGroup('group1', group1parametersDto),
createGroup('group2', group2parametersDto)
]

in your way you can create object with variables value this way . there was syntax error in your approach, template literals are not allowed for object key inside object directly
var group = "group",
Token1 = "123443423",
Token2 = "121414141"
var newObject =
{
[group + "1"] : {Token1 , Token2},
[group + "2"] : {Token1 , Token2},
[group + "3"] : {Token1 , Token2},
[group + "4"] : {Token1 , Token2}
}
console.log(newObject)
there is also more easy way to do same which is more conveneint
example below
var object = {},
Token1 = "123443423",
Token2 = "121414141"
object["group1"] = {Token1,Token2}
object["group2"] = {Token1,Token2}
object["group3"] = {Token1,Token2}
console.log(object)

Related

iterate through multinested json object with for loop

I've been trying to loop through a mulitnested json object but everytime it displays undefined. I've wanted to display playcount and the name of the song. I plan on using this with a bar chart.
I tried this expecting ['playcount', 'name']
function getData(){
$("#output").html("<b>hi there</b>");
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=drake&api_key=22102f7d3a814de0736edf670bd2c771&format=json',function(result){
console.log(result);
let testarray = result[0]['album'];
let newdata = [];
for (let i = 0; i < result.length; i++) {
testarray= result[i]['album']
console.log(testarray)
let item = []
item[0] = testarray[i]['playcount']
item[1] = testarray[i]['name']
newdata[j] = item
console.log(newdata);
}
console.log(newdata)
})
}
Let's first take a look at the data you are working with:
result = {
"topalbums":
{
"album":
[
{
"name": "So Far Gone",
"playcount": 12543719,
"mbid": "f05567cc-6ed3-40e0-bad1-7812478eecbe",
"url": "https://www.last.fm/music/Drake/So+Far+Gone",
"artist": { ... }
"image": [ ... ]
},
...
],
"#attr": { ... }
}
}
You are gettin an object that has a property with a key called topalbums. Top albums has two properties; an array called album and an object called #attr.
From the looks of it, you want to access the objects inside of the album array, and more specifically name and playcount.
Given the data you are working with I assume this is what you would be looking for:
let newdata =
[
{
"playcount": 123123
"name": "album name1"
},
{
"playcount": 12456543
"name": "album name2"
},
...
]
To achieve this you can alter your code in the following fashion:
function getData(){
$("#output").html("<b>hi there</b>");
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=drake&api_key=22102f7d3a814de0736edf670bd2c771&format=json',function(result){
console.log(result);
let albumArray = result["topalbums"]["album"]; // This gets you the album array
let newdata = [];
for (let i = 0; i < albumArray.length; i++) {
const albumSummary = {} // Create a new object
albumSummary["name"] = albumArray.name // Add name to the object
albumSummary["playcount"] = albumArray.playcount // Add playcount to the object
newdata.push(albumSummary) // Add the object to the array
}
console.log(newdata)
})
}
Alternatively, if you don't want an array of objects but an array of arrays like this [['playcount', 'name']...], you can alter the code above like this:
function getData(){
$("#output").html("<b>hi there</b>");
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=drake&api_key=22102f7d3a814de0736edf670bd2c771&format=json',function(result){
console.log(result);
let albumArray = result["topalbums"]["album"]; // This gets you the album array
let newdata = [];
for (let i = 0; i < albumArray.length; i++) {
const albumSummary = [] // Create a new array
albumSummary.push(albumArray.name) // Add name to the array
albumSummary.push(albumArray.playcount) // Add playcount to the array
newdata.push(albumSummary) // Add the array to the array
}
console.log(newdata)
})
}
Hope this helps!

Arrange array based on another array Javascript

I have reference array which has values ["a","b","c","d"] .and i have another array which is obtaining as part of API which is not very consistent format .i am pointing some examples below
case 1.`{
names : ["a"],
value : [ [0],[0],[2],[4],... ]
}`
case 2. `{
names : ["a","c"],
value : [ [0,2],[0,0],[2,3],[4,4],... ]
}`
the result could be in any combination
but my requirement is to assign the value of incoming result into another array
having index same as my reference array
for example : in
case 1
`
let finalArray = [["0",null,null,null],
["0",null,null,null],
["2",null,null,null].... ]
`
for case 2:
`let finalArray = [["0",null,"2",null],
["0",null,"0",null],
["2",null,"3",null].... ]
`
alse attaching a fiddle with my inputs below
jsfiddle link to problem
any suggestions?
i am trying to use minimal for loops for performance optimization
Hope this will be helpful.
var refArray = ["a","b","c","d"];
setTimeout(()=>{processResult({
"names" : ["a"],
"value" : [ [0],[0],[2],[4]]
})},2000);
setTimeout(()=>{processResult(
{
"names" : ["a","c"],
"value" : [ [0,2],[0,0],[2,3],[4,4]]
})},4000);
setTimeout(()=>{processResult(
{
"names" : ["d","c"],
"value" : [ [0,2],[0,0],[2,3],[4,4]]
})},6000);
function processResult (result) {
let res = result.value;
let resArray = res.map((el)=>{
let k=Array(refArray.length).fill(null);
refArray.forEach((e,i)=>{
let indx = result.names.indexOf(e);
if(indx>=0){
k[i] = el[indx]
}
});
return k;
})
console.log("result",resArray)
}
Below is what I could think of that would require least iterations.
var refArray = ["a", "b", "c", "d"];
setTimeout(()=>{processResult({
"names" : ["a"],
"value" : [ [0],[0],[2],[4]]
})},2000);
setTimeout(()=>{processResult(
{
"names" : ["a","c"],
"value" : [ [0,2],[0,0],[2,3],[4,4]]
})},4000);
setTimeout(()=>{processResult(
{
"names" : ["d","c"],
"value" : [ [0,2],[0,0],[2,3],[4,4]]
})},6000);
function processResult(result) {
//This map will contain max names matched in the result
var maxItemsFromResult = {};
//Find the indexes in refArray and fill map
//e.g. 1st- {0:0}, 2nd - {0:0, 1:2}, 3rd - {0:3, 1:2}
result.names.forEach((item, index) => {
let indexFound = refArray.indexOf(item);
if (indexFound > -1) {
maxItemsFromResult[index] = indexFound;
}
});
//for performance if no key matched exit
if (Object.keys(maxItemsFromResult).length < 1) {
return;
}
//This will be final result
let finalArray = [];
//Because finalArray's length shuld be total items in value array loop through it
result.value.forEach((item, itemIndex) => {
//Create a row
let valueArray = new Array(refArray.length).fill(null);
//Below will only loop matched keys and fill respective position/column in row
//i'm taking all the matched keys from current value[] before moving to next
Object.keys(maxItemsFromResult).forEach((key, index) => {
valueArray[maxItemsFromResult[key]] = item[index];//get item from matched key
});
finalArray.push(valueArray);
});
console.log(finalArray);
return finalArray;
}

Convert array from php to javascript

I have array from database with json_encode, like this :
"[{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]"
but how to make the array just display the record not with the field/column name, when i show in javascript like this :
javascript array :
{
"595e7d": "Elephant",
"701b03": "Bird",
"29a8c": "Lion"
}
whether it should be done in php or javascript?
thankyou
Handle with javascript:
function transfrom (arrs){
return arrs.reduce((init, arr) => {
init[arr.uid] = arr.name
return init
}
, {})
}
//usage
let arrs = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]
transfrom(arrs)
// {595e7d: "Elephant", 701b03: "Bird", 29a8c: "Lion"}
Or you can handle it with PHP:
<?php
$arr = array (
array('uid' =>"595e7d", "name"=>"Elephant"),
array("uid" =>"701b03", "name" =>"Bird"),
array("uid" =>"29a8c", "name" =>"Lion")
);
function transform($v1, $v2) {
$v1[$v2["uid"]] = $v2["name"];
return $v1;
}
echo json_encode(array_reduce($arr, "transform", array()));
// {
// "595e7d": "Elephant",
// "701b03": "Bird",
// "29a8c": "Lion"
// }
?>
If I understood it correctly, you are looking for something like
var arr = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}];
var out = {};
arr.forEach(function(obj){
var tempArr = Object.values(obj);
out[tempArr[0]] = tempArr[1];
});
console.log(out);
Please note that the code is not too generic and may require modification based on your actual requirement.

Inserting a nested object in meteor

I have this document saved in my mongo collection called exam
// meteor:PRIMARY> db.exam.find()
{
"_id" : "RLvWTcsrbRXJeTqdB",
"examschoolid" : "5FF2JRddZdtTHuwkx",
"examsubjects" : [
{
"subject" : "Z4eLrwGwqG4pw4HKX"
},
{
"subject" : "fFcWby8ArpboizcT9"
}
],
"examay" : "NrsP4srFGfkc5cJkz",
"examterm" : "5A5dNTgAkdRr5j53j",
"examclass" : "gYF2wE4wBCRy9a3ZC",
"examname" : "First",
"examdate" : ISODate("2016-05-07T22:41:00Z"),
"examresultsstatus" : "notreleased"
}
I am trying to select data from this document and saving it into another using this code.The aim is to have the examsubjects value in the document above to be the key in the document i am inserting into.
'click .reactive-table tr': function() {
Session.set('selectedPersonId', this._id);
var cursor = Exam.find({ _id:
Session.get("selectedPersonId")}).fetch();
cursor.forEach(function(doc){
for (i = 0; i < doc.examsubjects.length; i++) {
for (var prop in doc.examsubjects[i]) {
console.log("obj." + prop + " = " + doc.examsubjects[i][prop]);
var subj = doc.examsubjects[i][prop];
Told.insert({
examschoolid:"sms",
examname:doc.examname,
examsubjects: [{subj : "0"}],
examay:doc.examay,
examterm:doc.examterm,
examclass:doc.examclass,
examdate:doc.examdate
});
}
}
});
},
When the code runs,the variable subj that holds the subjects value just inserts subj not knowing its a variable like this
{
"_id" : "5yjwFanBAupgu9GHq",
"examschoolid" : "sms",
"examname" : "First",
"examsubjects" : [
{
"subj" : "0"
}
],
"examay" : "NrsP4srFGfkc5cJkz",
"examterm" : "5A5dNTgAkdRr5j53j",
"examclass" : "gYF2wE4wBCRy9a3ZC",
"examdate" : ISODate("2016-05-07T22:41:00Z")
}
Why is the variable not being seen as a variable?.
Edit
'click .reactive-table tr': function() {
Session.set('selectedPersonId', this._id);
var cursor = Exam.find({ _id: Session.get("selectedPersonId")}).fetch();
cursor.forEach(function(doc){
var sq = function(){
for (i = 0; i < doc.examsubjects.length; i++) {
for (var prop in doc.examsubjects[i]) {
const subj = doc.examsubjects[i][prop];
let subject = {};
subject[subj] = "0";
return [subject];
}
}
}
console.log(sq());
Told.insert({
examschoolid:"sms",
examname:doc.examname,
examsubjects: sq(),
examay:doc.examay,
examterm:doc.examterm,
examclass:doc.examclass,
examdate:doc.examdate
});
});
//Uncaught TypeError: cursor.count is not a function
},
The updated code almost works,but only inserts 1 record.
That's how JSON works, it takes keys literally. Fix it by using ES6 brackets notation:
examsubjects: [{
[subj] : "0"
}],
This is because it is treated as a key in a literal object.
If you want to have subj's value as your key, you will need to use the bracket notation, creating the object beforehand:
const subj = doc.examsubjects[i][prop];
let subject = {};
subject[subj] = "0";
Told.insert({
examschoolid:"sms",
examname:doc.examname,
examsubjects: [subject],
...
});

nesting multiple level of array with associative

data = [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
how to format the above array into this
var name = {
"user": {
"name" : [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
}
}
I tried var name['name'] = data and don't know how to wrap the result. I want to wrap the result with 'user' as it assoc.
You can't assign properties as you create the object. Either first create the object and then set the property:
var name = {};
name.user = { name : data };
or create the entire object at once:
var name = { user: { name: data } };
var data = [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
var name = {
"user": {
"name" : data
}
}

Categories