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
Related
I have an element containing objects , i want to get all the values of 2 properties from the element example(data.number & data.name)
just for clarification it holds the data in this format " 0 { number:30 , name : joseph } 1 { number: 340, name : micheal} "aplogies for confusion
and i want to string them together
example( value of data.number[0] & value of data.name[0] , value of data.number[1] & value of data.name[1] and so on ... )
here is what i have come up with so far:
let finalarray = []
for(let i=0; i<1; i ++){
let nationNumber = Object.keys(myarraywiththedata).map(function(key){ return myarraywiththedata[key].number });
finalarray.push(nationNumber)
let nationName = Object.keys(myarraywiththedata).map(function(key){return myarraywiththedata[key].number });
finalarray.push(nationName)
}
but this doesn't work obviously
will accept edits to this post for readability
try this (assuming the properties in each object value are actually called "number" and "name").
let finalarray = Object.values(myarraywiththedata).map(({number, name}) =>
`${number} & ${name}`
);
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
I have array from database with json_encode, like this :
"[{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]"
but how to make the array just display the record not with the field/column name, when i show in javascript like this :
javascript array :
{
"595e7d": "Elephant",
"701b03": "Bird",
"29a8c": "Lion"
}
whether it should be done in php or javascript?
thankyou
Handle with javascript:
function transfrom (arrs){
return arrs.reduce((init, arr) => {
init[arr.uid] = arr.name
return init
}
, {})
}
//usage
let arrs = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]
transfrom(arrs)
// {595e7d: "Elephant", 701b03: "Bird", 29a8c: "Lion"}
Or you can handle it with PHP:
<?php
$arr = array (
array('uid' =>"595e7d", "name"=>"Elephant"),
array("uid" =>"701b03", "name" =>"Bird"),
array("uid" =>"29a8c", "name" =>"Lion")
);
function transform($v1, $v2) {
$v1[$v2["uid"]] = $v2["name"];
return $v1;
}
echo json_encode(array_reduce($arr, "transform", array()));
// {
// "595e7d": "Elephant",
// "701b03": "Bird",
// "29a8c": "Lion"
// }
?>
If I understood it correctly, you are looking for something like
var arr = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}];
var out = {};
arr.forEach(function(obj){
var tempArr = Object.values(obj);
out[tempArr[0]] = tempArr[1];
});
console.log(out);
Please note that the code is not too generic and may require modification based on your actual requirement.
I have an object, with nested objects. How do I target a specific index of the object and loop through all the nested values of image. As you will note the length of the nested objects vary.
Target example: productArray[0].image = test1.png, test2.png, test3.png
var products = [
//item1
{
identifier: "item-0",
image: {
"img1": "test1.png",
"img2": "test2.png",
"img3": "test3.png"
}
},
//item2
{
identifier: "item-1",
image: {
"img1": "test1.png",
"img2": "test2.png"
}
},
//item3
{
identifier: "item-2",
image: {
"img1": "test1.png",
"img2": "test2.png",
"img3": "test3.png",
"img4": "test4.png",
"img5": "test5.png",
"img6": "test6.png",
"img7": "test7.png"
}
}
];
We can do this. What you need to do is a simple loop through the object at a specific index, or you can target them all. Note that the image object is not an array, so it will not have an accurate length property.
Target all indexes:
for(var i = 0; i < products.length; i++) {
console.log("Item: " + i);
var images = products[i].image;
for(var a in images)
console.log(images[a]);
}
Target specific:
for(var i in products[0].image)
console.log(products[0].image[i]);
I used a for loop here, but you can use a while loop if you would like.
example
Steps:
You need to iterate over your original array of products. products
Each element (product) will be in format { identifier: "", image : {"img1" : "img2", ..}} products[i]
You get the image property of current product - this is an object. products[i].image
Now you need to iterate over the properties of the image object. products[i].image[j]
Code:
for(var i = 0; i < products.length; i++)
{
for(var j in products[i].image)
{
// Here you have all the images for the current product.
// You can print them, group them or whatever you want to do with them
console.log(products[i].image[j]);
}
}
Also you can change the code (introduce variables) to be more readable.
var strs = (function( obj ) {
var ret = [];
for( im in obj ) {
ret.push( obj[im] );
//You could access each image URL here
//ad strs in the end will have all of them
//comma-separated after this code completes
// im is the key, obj[ im ] the value
}
return ret.join(',');
})( products[0].image );
console.log( strs );
WORKING JS FIDDLE DEMO
Here is another way of doing this, with newer functions in ECMAScript 5
var images = Object.keys(products[2].image).map(function(key){
return products[2].image[key]
})
console.log(images) // Returns: ["test1.png", "test2.png", "test3.png", "test4.png", "test5.png", "test6.png", "test7.png"]
How It Works:
Object#keys returns an array of key names. Array#map creates a new array using the keys from Object#keys. By looking up the key from the object you get the value, which will be the image name.
JS FIDDLE
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