Making Object using JSON.stringify - javascript

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

Related

How to get JSON object in array?

var data = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
Here I have posted my JSON data. I want to get all the defaultValue in JSON/Array format. My output should be like-
defaultValues:['Size30','Black','Low']
How to manage that in the foreach loop?
my code :
var otherSelectedOption;
angular.forEach(data, function(optionValue, optionKey) {
if (optionValue.defaultValue.text) {
otherSelectedOption = (optionValue.defaultValue.text);
}
selectedOption = {defaultValues: otherSelectedOption};
console.log(selectedOption);
});
Your JSON is not valid, since objects are not separated by comma ,
Suppose this is the JSON
var obj = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
try
var arr = JSON.parse(obj).map( function(item){
return item.defaultValue;
});

Handle Json data and pass it to object for further use

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

How to properly use JSON.parse in this sample code (string to array)?

I'm trying to store an array in StriptProperties converting it to a string and recovering this way:
var personDataArr = ["Adam", "male", "programmer"];
function myFunction() {
var personDataStr = JSON.stringify(personDataArr);
ScriptProperties.setProperty('personData', personDataStr);
var personData = ScriptProperties.getProperty('personData');
personData = JSON.parse("[" + personData + "]");
Logger.log("personData[0] = " + personData[0]);
}
But when I log Logger.log("personData[0] = " + personData[0]); I get personData[0] = Adam,male,programmerinstead of Adam. Why? How to get, instead, the first element of the array?
You need to remove square brackets ( [] ) from JSON.parse function:
personData = JSON.parse( personData );
This happens because you create multidimentional array ant it looks in final result as:
[["Adam", "male", "programmer"]]
This is why 0 index of that array return Array for you and not Adam value

Jquery reading several array parameters from url

I have the following URL:
http://mydomain/Forwards?searchValue[]=Nike+Webstore&searchValue[]=Bodyman&category_filter[]=Animals+%26+Pet+Supplies&category_filter[]=Fashion&country_filter[]=Aland+Islands&country_filter[]=American+Samoa
This url contains alot of paramters that are sent as an array:
Now i wish to get each individual array and its value out
in the above example the result should be something like this:
searchValue = array(
[0] = 'Nike Webstore'
[1] = 'Bodyman'
);
category_filter = array(
[0] = 'Animals & Pet Supplies'
[1] = 'Fashion'
);
country_filter = array(
[0] = 'Aland Islands'
[1] = 'American Samoa'
);
is it possible to get it out like this and if so how? i have attempted with the following:
decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
However this only returned 1 value (Nike Webstore) in my example.
as parameters are an array. the below code will work just fine..
// our test url
var url ="http://mydomain/Forwards?searchValue[]=Nike+Webstore&searchValue[]=Bodyman&category_filter[]=Animals+%26+Pet+Supplies&category_filter[]=Fashion&country_filter[]=Aland+Islands&country_filter[]=American+Samoa" ;
// filtering the string..
var paramsList = url.slice(url.indexOf("?")+1,url.length) ;
var filteredList = paramsList.split("&") ;
// an object to store arrays
var objArr = {} ;
// the below loop is obvious... we just remove the [] and +.. and split into pair of key and value.. and store as an array...
for (var i=0, l=filteredList.length; i <l; i +=1 ) {
var param = decodeURIComponent(filteredList[i].replace("[]","")).replace(/\+/g," ") ;
var pair = param.split("=") ;
if(!objArr[pair[0]]) { objArr[pair[0]] = [] ;}
objArr[pair[0]].push(pair[1]);
}
console.log(objArr);
which will give us....
[object Object] {
category_filter: ["Animals & Pet Supplies", "Fashion"],
country_filter: ["Aland Islands", "American Samoa"],
searchValue: ["Nike Webstore", "Bodyman"]
}
hope this helps.. :D
Try to see if this pattern works for you
(?:\?|&)(.+?)=([A-Z+%0-9]+)
Example here

how to create a hashtable dynamically in javascript

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

Categories