I have a web application which will return JSON as response and its response is something like following :
{"album1" : "track1" , "album1" : "track2" , "album1" : "track3" , "album2" : "track1"}
please note the architecture of back end is out of my hand and I'm not able to change the way it create json (repeated key)
so I want to create a hashtable in javascript the idea of my hashtable should be something like :
"album1" : ["track1" , "track2" , "track3"]
my question is how can I create such behavior in javascript?
I know how to create hashmap but not hashtable.
Well if this structure remains intact, you could probably hack together a function which does it. Something on the lines as below
var response = '{"album1" : "track1" , "album1" : "track2" , "album1" : "track3" , "album2" : "track1"}'
.replace(/}?{?/g, '');
var sanitisedData = {};
var transform = response.split(',').map(function(item){
return JSON.parse('{' + item + '}');
}).forEach(function(item){
var key = Object.keys(item)[0];
if(!sanitisedData [key]) sanitisedData [key] = [];
sanitisedData [key].push(item[key]);
});
//output - {"album1":["track1","track2","track3"],"album2":["track1"]}
Related
I can't seem to access object data after JSON.stringify. I'm getting undefined with console.log(data[0].colour)
let data = [];
let colours = ['#340068' , '#ff6978' , '#fffcf9' , '#b1ede8' , '#6d435a']
let names = ['coffee' , 'cake' , 'holiday' , 'break' , 'lunch']
var result = colours.map(function(element , i){
data.push(`{'colour' : '${element}','name' : '${names[i]}'}`)
})
Thanks in advance
JSON.stringify(data)
console.log(data[0].colour)
First and Foremost single quotes
'
represents character.... for string use double quotes
"
Secondly
JSON stringify doesn't get objects...
JSON.PARSE on a valid JSON String makes the JSON object..
let data = [];
let colours = ['#340068' , '#ff6978' , '#fffcf9' , '#b1ede8' , '#6d435a']
let names = ['coffee' , 'cake' , 'holiday' , 'break' , 'lunch']
var result = colours.map(function(element , i){
var item = `{"colour" : "${element}","name" : "${names[i]}"}`;
var itemstr = JSON.stringify(item);
var itemObj = JSON.parse(itemstr);
data.push(itemObj) //replaced '
})
var FirstItemOBj = JSON.parse(data[0]);
console.log(FirstItemOBj.colour); // gets the first object of strings
For instance I have some JSON data like below (The JSON data is just an example, I just want to give out some fake, make up and wrong format JSON as example)
cata :[{
name:test1,
data:['abc1, abc2' , 'abc3,abc4']
}
name:test2,
data:['abc5, abc6' , 'abc7,abc8']
}]
And indeed I need to render it to frontend, therefore I made a new object and try to push data into it
var name = "";
var key= [];
for(var i=0;i<2;i++){
name .push(cata[i].name)
key.push(cata[i].data.join(' + '));
}
var rehandle = {
name : name,
key : key
}
The above is just how i do it now, and which do no provide the desire result, i want to know how could i restore it so i can change the format from
['abc5, abc6' , 'abc7,abc8']
to
abc5+abc6 , abc7+abc8
UPDATE version of the question:
I think i better explain it step by step:
I have some raw data
I have a row of "data" in each set of data
(E.g:data:['abc1, abc2' , 'abc3,abc4'])
I want to change it's format to abc1+abc2 , abc3+abc4 and store it to another variable
I will pass the variable store abc1+abc2 , abc3+abc4 to an object
5.Render it one by one in a table
UPDATE 2
I have seen #pill's answer, am i able to render the data like
for(var i=0;i<cata.length;i++){
var trythis = trythis + '<td>'+name[i]+'</td>' + '<td>'+data[i]+'</td>'
}
To format your data from
['abc5, abc6' , 'abc7,abc8']
to
abc5+abc6 , abc7+abc8
you'd simply use
data.map(k => k.split(/,\s*/).join('+')).join(' , ')
or the ES5 version
data.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , ');
For example...
var cata = [{"name":"test1","data":["abc1, abc2","abc3,abc4"]},{"name":"test2","data":["abc5, abc6","abc7,abc8"]}];
var rehandle = cata.reduce(function(o, d) {
o.name.push(d.name);
o.key.push(d.data.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , '));
return o;
}, {
name: [],
key: []
});
console.log('rehandle:', rehandle);
Note that I had to fix up your data formatting
Question 1
Assume I am getting a JSON object scope.tagSet, which is in the following format.
{ Tags : [
{"TagID" : "ID1" , "TagName" : "Name1"},
{"TagID" : "ID2" , "TagName" : "Name2"},
{"TagID" : "ID3" , "TagName" : "Name3"}
]
}
Inside an angular directive I am making an array of all the values in TagName as follows.
for(var i= 0; i < scope.tagSet.Tags.length; i++){
scope.tagNames[i] = scope.tagSet.Tags[i].TagName;
}
Is looping through and assigning each the only option here? Or is there any other way which is more efficient.
Question 2
Say that I've got the array tagNames[] My next job is to perform a search to check if a given variable varString exists in the array tagNames[] and return true or false accordingly.
I know that scope.tagNames.indexOf(varString) will return -1 when there are no matches,
but is it the angular way? Are these approaches considered good practice?
What you can do is make a lookuplist. In javascript you can use the object:
function arrayToLookup(a, key) {
var o = {};
for (var i = a.length; i--;) {
o[a[i][key]] = true;
}
return o;
}
Use it like this
var lookupList = arrayToLookup(scope.tagSet.Tags, "TagName");
now you can check if it is available by doing this:
lookupList["Name1"];//returns true
Why are you so keen to do it the angular way? What if you one day decide to dump angular? That's more likely than keeping angular but dumping JS. This is the JS way:
scope.tagNames = scope.tagSet.Tags.map( function (i) {return i.TagName;} )
Then use indexOf as you suggested at the outset.
You could use the angular-filtermodule to check if your array contains the given item:
$scope.items = [
{"TagID" : "ID1" , "TagName" : "Name1"},
{"TagID" : "ID2" , "TagName" : "Name2"},
{"TagID" : "ID3" , "TagName" : "Name3"}
]
// returns true
$scope.Name1 = $filter('contains')($scope.items,'TagName == "Name1"');
// returns false
$scope.Name4 = $filter('contains')($scope.items,'TagName == "Name4"');
Here is a working plunker
Use this
var arrayNew=[];
angular.forEach(scope.tagSet.Tags, function(value, key) {
arrayNew[i] = value.TagName;
});
scope.tagNames=arrayNew;
i'm trying to create object named client. and put it into a array. And after this, read the name of the 1st client.
Exemple :
client1 {nom : "marco", prenom : "chedel", adresseMail : "ssss#ggg.com"};
and put this client into an array like bellow.
listClients[client1]
what i did :
var listClients = [];
var client1 = {nom : "chedel",prenom:"Marco",adresseMail:"marco#gmail.com"};
listClients.push(client1);
var client2 = {nom : "De Almeida",prenom:"Jorge",adresseMail:"jorge#gmail.com"};
listClients.push(client2);
function afficheClients(tableau){
for (i=0;i<tableau.length;i++)
{
var c = tableau[i];
document.write(c[adresseMail]);
// This ^^ doesn't work, it says :adresseMail isn't definied in c
}
}
afficheClients(listClients);
You're treating adressMail as a variable and not as a string:
use
document.write(c["adresseMail"]);
There are two ways to access properties of an object:
obj.prop
obj['prop']
You are doing the following mixture which doesn't work: obj[prop].
Fix your code to c.adresseMail or c['adresseMail'] and it will work.
Either reference it using a string:
document.write(c['adresseMail']);
or using dot notation:
document.write(c.adresseMail);
And, yes - document.write should be avoided.
{"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]}
How do i write the code to read the teamid and teamname so as to store them in seperate variables?
Please Help!
If it is a JSON string, parse it...
var obj = jQuery.parseJSON(jsonString);
Then work with the information
obj.TeamList[0].teamid;
obj.TeamList[0].teamname;
TeamList is an array so if you have more than one "team" you'll need to loop over them.
You have an object containing an array TeamList, which has one object as its elements:
var tl = {"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]};
var id = tl.TeamList[0].teamid;
var name = tl.TeamList[0].teamname;
If the example you have posted in contained as a string you can parse it like so with javascript...
var jsonObject = JSON.parse(myJsonString);
you can then access your array like so...
jsonObject.TeamList
and each item in TeamList...
jsonObject.TeamList[i].teamid
jsonObject.TeamList[i].teamname
finally assuming you have one item in TeamList and making an attemp to directly answers you question...
var teamid = jsonObject.TeamList[0].teamid;
var teamname = jsonObject.TeamList[0].teamname;
hope that makes sense
in which language? Basically after parsing using json you would do something like this on the result:
result["TeamList"][0]["teamname"] to get teamname and result["TeamList"][0]["teamid"] to get teamid.
If you can use json_decode, like this :
$content = '{"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]}';
$json = json_decode($content);
$obj = $json->{'TeamList'}[0];
print $obj->{'teamid'}."//".$obj->{'teamname'};
You had tagged your question as jQuery? We're you wanting to display this information on a page?
Given some sample html:
<label>Team ID:</label>
<div id="teamid"></div>
<label>Team Name:</label>
<div id="teamname"></div>
And a little jquery:
var obj = {"TeamList" : [{"teamid" : "2","teamname" : "Milan"}]};
$('#teamid').html(obj.TeamList[0].teamid);
$('#teamname').html(obj.TeamList[0].teamname);
Would allow you to accomplish this. As others have pointed out you would need to iterate over the collection if there were multiple teams.