Changing forEach loop to for-loop in javascript - javascript

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]);

Related

Javascript - Adding new element to array using for loop

I'm trying to convert url. Using for loop to extract Acura, Audi. Here what I got so far:
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
makes.push(make);
console.log(makes)
}
};
The result is
[ 'Acura' ]
[ 'Acura', 'Audi' ]
As you see it has one more array. Is there a way to get only [ 'Acura', 'Audi' ]?
FYI there's a native solution for getting values a from query string, check URLSearchParams
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const makes = new URLSearchParams(newSrpParams).getAll('make');
console.log(makes);
That is happening because you are logging the array inside the for loop. If you move it outside you will get
['Acura', 'Audi']
The Code:
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
console.log(newSrpParamsArray)
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
console.log(make)
makes.push(make);
}
};
console.log(makes) // The change
You were consoling the results inside the if statement it will run two times. So as a result make[] array print two times. That's why you get the two arrays.
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
makes.push(make);
}
};
console.log(makes)
Make sure to console make[] from outside of the for a loop. That's only. I couldn't see any other wrong line in your code.
Why not use URLSearchParams?
and you can replace the URL with window.location.href
let url = new URL(`http://localhost?year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000`)
let params = new URLSearchParams(url.search).getAll("make")
console.log(params)

Convert JSON data into javascript object with key and value

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;
}

How to convert json to java script array?

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.

How to "clean" an array in javascript?

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']

javascript how to find number of children in an object

is there a way to find the number of children in a javascript object other than running a loop and using a counter? I can leverage jquery if it will help. I am doing this:
var childScenesObj = [];
var childScenesLen = scenes[sceneID].length; //need to find number of children of scenes[sceneID]. This obviously does not work, as it an object, not an array.
for (childIndex in scenes[sceneID].children) {
childSceneObj = new Object();
childSceneID = scenes[sceneID].children[childIndex];
childSceneNode = scenes[childSceneID];
childSceneObj.name = childSceneNode.name;
childSceneObj.id = childSceneID;
childScenesObj .push(childSceneObj);
}
The following works in ECMAScript5 (Javascript 1.85)
var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2
If that object is actually an Array, .length will always get you the number of indexes. If you're referring to an object and you want to get the number of attributes/keys in the object, there's no way I know to that other than a counter:
var myArr = [];
alert(myArr.length);// 0
myArr.push('hi');
alert(myArr.length);// 1
var myObj = {};
myObj["color1"] = "red";
myObj["color2"] = "blue";
// only way I know of to get "myObj.length"
var myObjLen = 0;
for(var key in myObj)
myObjLen++;

Categories