I have below json parse data and i am trying to convert it to javascript object
usrPrefs
[Object { name="mystocks", value="500400,532500,500180,500312,500325"},
Object { name="mystocksname", value="Tata Power,Maruti Suzuki...NGC,Reliance Industries"},
Object { name="refresh_secs", value="600"}]
i am trying to convert this to something like below
myparam = {
mystocks:500400,532500,500180,500312,500325,
mystocksname:Tata Power,Maruti Suzuki...NGC,Reliance Industries
....
}
how i can do that in javascript something like using loop or any build in function, i started learning javascript and i am stuck here...
thank you in advance.
Regards,
Mona
You could use the reduce function in order to achieve that:
var myparam = usrPrefs.reduce(function(a, b){
a[b.name] = b.value;
return a;
}, {});
You might choose to use array instead of string, its more convenient for you to use
function toMap(usrPrefs){
var result = {};
for(var i = 0 ; i < usrPrefs.length ; i++){
var obj = usrPrefs[i];
var array = obj.value.split(',').trim();
result[obj.name] = array;
}
return result;
};
Try this code:
var myparam = {};
for (var i = 0; i < usrPrefs.length; i++) {
myparam[usrPrefs[i].name] = usrPrefs[i].value;
}
Related
I currently have a forEach loop like this.
var videoUrls ={};
ytplayer.config.args.url_encoded_fmt_stream_map.split(',')
.forEach(function(item) {
var obj = { };
item.split('&')
.forEach(function(param) {
param = param.split('=');
obj[param[0]] = decodeURIComponent(param[1]);
});
videoUrls[obj.quality] = obj;});
Since IE is not supporting forEach loop, I tried to convert this to for loop.
var videoUrls ={};
var typea= ytplayer.config.args.url_encoded_fmt_stream_map.split(',');
for (var item=0; item<typea.length; item++){
var obj= {};
var typeb= typea[item].split('&');
for (var param=0; param<typeb.length; param++){
typeb[param]= typeb[param].split('=');
obj[typeb[0]] = decodeURIComponent(typeb[1]);
}
videoUrls[obj.quality]= obj;
}
But when I run the script the results were different. What did i do wrong?
Thanks in advance.
it should be:
typeb[param]= typeb[param].split('=');
obj[typeb[param][0]] = decodeURIComponent(typeb[param][1]);
Because the other loop is:
param = param.split('=');
obj[param[0]] = decodeURIComponent(param[1]);
Not:
obj[item.split("&")[0]] = decodeURIComponent(item.split("&")[1])
If it's still not clear, here is a simpler explanation:
typeb === item.split("&");
typeb[param] === param;
The problem is here:
for (var param=0; param<typeb.length; param++) {
typeb[param]= typeb[param].split('=');
obj[typeb[0]] = decodeURIComponent(typeb[1]);
}
You're overwriting an element of the array you're iterating over (typeb[param]) and then using a hardcoded index into the same array (typeb[1])
Should be more like:
for (var param=0; param<typeb.length; param++) {
var arr = typeb[param].split('=');
obj[arr[0]] = decodeURIComponent(arr[1]);
}
And you cannot use library like jQuery? It is for this reason jQuery is built. If you cannot then i think this is what you need to do
obj[typeb[param][0]] = decodeURIComponent(typeb[param][1]);
I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>
I have the json string like,
string js=[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]
And I need to convert this into like the following format using java script.
[['Pini',111],['Yaniv',123],['Yoni',145]]
How to convert the json string into javascript array using javascript function?
I think something like this:
var ret = [];
for (var i = 0; i < js.length; i++) {
ret.push([js[i].Name, js[i].ID]);
}
// ret holds your array of arrays
Or something like:
var ret = $.map(js, function (el, i) {
return [[el.Name, el.ID]];
});
An example of both: http://jsfiddle.net/RNY8M/
You can do like this
JsFiddler Demo of below code
var JSONObject = {"results":[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]};
var Users= [];
$.each(JSONObject.results, function(i, obj)
{
alert(obj.Name);
alert(obj.ID);
Users.push([obj.Name, obj.ID]);
});
For this kind of transformations I always prefer using UnderscoreJs which is an utility-belt library (mainly for object/array transformations) for Javascript. I think that it provides great functions that make life easier, allowing javascript developers to be more productive and to achieve a better legibility for the resulting code.
Here is the solution with underscore (extended):
var js=[{"Name":"Pini","ID":"111"},
{"Name":"Yaniv","ID":"123"},
{"Name":"Yoni","ID":"145"}]
var names = _.pluck(js, 'Name');
var ids = _.pluck(js, 'ID');
var result = _.zip(names, ids)
And you achive the desired result:
[['Pini',111],['Yaniv',123],['Yoni',145]]
Solution in one line with underscorejs:
var result = _.zip(_.pluck(js, 'Name'), _.pluck(js, 'ID'))
Hope it helps!
Here's a solution that will work for a simple object (not deep objects, though.... but I'll leave that for you to implement).
http://jsfiddle.net/eUtkC/
var js = [{
"Name": "Pini",
"ID": "111"},
{
"Name": "Yaniv",
"ID": "123"},
{
"Name": "Yoni",
"ID": "145"}]
function obj2arr(obj) {
var i, key, length = obj.length,
aOutput = [],
aObjValues;
for (i = length - 1; i >= 0; i--) {
aObjValues = [];
for (key in obj[i]) {
if (obj[i].hasOwnProperty(key)) {
aObjValues.push(obj[i][key]);
}
}
aOutput.push(aObjValues);
}
return aOutput;
}
document.write(JSON.stringify(obj2arr(js)))
EDIT
Here's a version using Array.prototype.map:
http://jsfiddle.net/eUtkC/1/
function obj2arr(obj) {
var key, aOutput = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) {
aOutput.push(obj[key]);
}
}
return aOutput;
}
document.write(JSON.stringify(js.map(obj2arr)))
I correct my solution, I hadn't read well the specs (my fault):
var jsonArray = [{"Name":"Pini","ID":"111"}, {"Name":"Yaniv","ID":"123"}, {"Name":"Yoni","ID":"145"}];
var jsonConverted = {};
$(jsonArray).each( function() {
jsonConverted.push([ this.Name, this.ID ]);
});
This solution uses jQuery.
I have code that calls a WCF service and returns a JSON string to the client. Below is the javascript function I am trying to use to parse the JSON but can not figure out how to traverse it.
Here is the function
loadDropDown: function(result, ddl, defaultItem) {
var _data = result.get_object();
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;
}
Here is the JSON
{
"d": "[{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Lexus\",\"Value\":\"Lexus\"},{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Acura\",\"Value\":\"Acura\"}]"
}
any suggestions on why this is not working? Note: I am not using jquery in the solution.
You shouldn't be generating that json. Instead, you should be outputting
{
"d": [{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Lexus","Value":"Lexus"},{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Acura","Value":"Acura"}]
}
(quotes removed from "d" value)
There's no reason to convert json to a string before putting it in a json object! Just put the json straight in.
You should be able to just eval() the object (or use JSON parsing from Crockford) and access your properties in regular object notation. You may need to unescape your identifiers first, though.
You need to do eval(_data) before you use it as a javascript array.
for ex:
var _rawdata = result.get_object();
var _data = eval(_rawdata);
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;
I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']