Javascript - Adding new element to array using for loop - javascript

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)

Related

Get payload from String

I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.

How can I create an array from an input string using JavaScript?

Currently I have a PHP page returning some values. The data is something like this:
08-30-2018, in
08-29-2018, out
08-28-2018, in
08-27-2018, in
How can I create a custom array in Javascript with the values above to be similar as this array below:
var system = [
['08-30-2018', 'in'],
['08-29-2018', 'out'],
['08-28-2018', 'in'],
['08-27-2018', 'in']
];
I have tried array.push, but it does not create an array like above.
What should I do? Can you help me? Thank you!
You can use multi-dimensional arrays in JavaScript
var system = [];
var output = "08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in";
var items = output.split("\n");
for(i=0; i<items.length; i++){
var data = items[i].split(",");
var item = [];
item.push(data[0].trim());
item.push(data[1].trim());
system.push(item);
}
console.log(system);
You could also parse this kind of input using regular expressions:
const input = '08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in';
const regex = /(\d{2}-\d{2}-\d{4}), (in|out)/g;
let system = [];
let match;
while ((match = regex.exec(input)) !== null) {
system.push([match[1], match[2]]);
}

Split Javascript String

I've got a javascript string called cookie and it looks like that:
__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en
It could have more ;xxxxxx; but always the entries will be surrounded by ;.
Now i want to split my var into a array and search for the entry "language=xy", this entry should be saved in "newCookie".
Could anyone help me please i'm completly stucked at splitting the var into a array and search for the entry.
Thanks for helping and sharing
var cookie = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;';
var cookie_array = cookie.split(';'); // Create an Array of all cookie values.
// cookie_array[0] = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10'
// cookie_array[1] = '__utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)'
// cookie_array[2] = '__utmb=43024181.19.10.1349761990'
// cookie_array[3] = '__utmc=43024181'
// cookie_array[4] = 'language=en'
var size = cookie_array.length; // Get Array size to prevent doing lookups in a loop.
for (var i = 0; i < size; i++) {
var keyval = cookie_array[i].split('='); // Split into a key value array
// What we're trying to find now.
// keyval[0] = 'language'
// keyval[1] = 'en'
if (keyval[0] == 'language') { //keyval[0] is left of the '='
//write new cookie value here
console.log('Language is set to ' + keyval[1]); // keyval[1] is right side of '='
}
}
Hope this helps ya out.
For more info on the split() method look at split() Mozilla Developer Network (MDN) documentation
Use a simple regexp for this:
var getLanguage = function(cookie){
var re = new RegExp(/language=([a-zA-Z]+);/);
var m = re.exec(cookie);
return m?m[1]:null;
};
var lang = getLanguage('__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;');
// lang = "en"

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