Create multidimensional array from string [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse query string in JavaScript
I want to create an options array from a string. How can i create an array as
{
width : 100,
height : 200
}
from a string like
'width=100&height=200'
Is there to create such arrays?

That's not an array, it's an object. It's not multidimensional either.
But anyway, you can split the string on the & separator and then split each item on the =:
var input = 'width=100&height=200',
output = {},
working = input.split("&"),
current,
i;
for (i=0; i < working.length; i++){
current = working[i].split("=");
output[current[0]] = current[1];
}
// output is now the object you described.
Of course this doesn't validate the input string, and doesn't cater for when the same property appears more than once (you might like to create an array of values in that case), but it should get you started. It would be nice to encapsulate the above in a function, but that I leave as an exercise for the reader...

Try this:
JSON.parse('{"' + decodeURI(myString.replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')

Related

i want to set key as number in my key value pair set [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed last year.
var i=0;
var mainObj={};
while(i<2){
var obj={};
obj.x ="data";
obj.y= "data";
mainObj.i=obj
i=i+1;
}
console.log(JSON.stringify(mainObj));
output :- {"j":{"x":"data"."y":"data"}}
{"j":{"x":"data"."y":"data"}}
Expected Output : {0:{"x":"data"."y":"data"},1:{"x":"data"."y":"data"}}
how to achieve this expected output i need the same output key should be number either in string format or number format
Try mainObj[i] = obj instead of mainObj.i = obj to use a computed key.

Make a new array with one element of a multidimenional array using JavaScript [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 3 years ago.
I have a JSON object in a JavaScript function:
[{"PMID":31206477,"MemberID":1287,"recID":6352},
{"PMID":31202264,"MemberID":1245,"recID":5974},
{"PMID":31201299,"MemberID":1184,"recID":3012},
{"PMID":31196160,"MemberID":1241,"recID":3833}]
That is saved to an Multi-dimensional Array
Is there a better way that I can make a make a new Array with only the PMID element without looping and building it. I know that this question is close to a duplicate but I'm not interested in a merge or a concat. Currently I'm doing
var newArray = [];
for (var i = 0; i < this.pmidList.length; i++) {
newArray.push(this.pmidList[i]["PMID"]);
}
This question maybe a duplicate but if the average person can't find it based upon the title then it should not be considered a duplicate. The solution is the same but the question titles are much different.
You can use the Array.map function.
const input = [{"PMID":31206477,"MemberID":1287,"recID":6352},
{"PMID":31202264,"MemberID":1245,"recID":5974},
{"PMID":31201299,"MemberID":1184,"recID":3012},
{"PMID":31196160,"MemberID":1241,"recID":3833}];
const output = input.map(item => item.PMID);
Documentation

Counting Object Length based on key value [duplicate]

This question already has answers here:
How can I only keep items of an array that match a certain condition?
(3 answers)
Closed 8 years ago.
I have a JS object/ associative array with some values:
var array =[
{val:1,ref:10,rule:100},
{val:1,ref:12,rule:120},
{val:2,ref:13,rule:165},
];
And I want to perform a .length, but want to be able to slice based on one of the keys (for instance val == 1). I want the length of values with val 1 rather than the length of the entire object. I have looked through the references material and could not find a satisfactory answer and I am unsure if this is feasible.
array.val==1.length = 2
Something like that...
You want to .filter the array for elements that match some predicate:
var filteredArray = array.filter(function(element) { return element.val == 1 })
filteredArray.length // = 2
filter applies the callback function to each element in the array, and the new filtered array contains all elements from original array for which the filter callback function returned true. Here, the function returns true for all elements with a val property of 1.
You need to use a .filter():
array.filter(function(v){return v.val==1}).length

Object Obect array Json.stringify string array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I had a object object array which i used JSON.stringify() on i can now see what's in my array but when i do arr[0] etc it only outputs one letter.
arr = {"hello":"yes","because":"no"}
arr[0] =h
I want it to output the whole of the value not just the first letter
My code
var clientContext = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
MyProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(MyProperties);
clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
},
getMyNewsChoicesSuccess = function () {
//get the news choice by actually fieldname
var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
$('#NBStest').text(MyChoices);
},
You can get the first element from your json string like this
JSON.parse(json_str)[0]
but in the example you have, the first element is "yes" and its index is "hello" , which means you can't get the first element by the index 0 , however you can get it by its property name like this
arr.hello = "yes";
// or
arr['hello'] = "yes";
if you want to get the hello which is the key , you have to use this loop
for (key in arr)
console.log(key);
// it will print 'hello' and then 'because'
Well its not an array anymore, its a string. arr[0] will return the first letter.
If you want to get the objects from it you need to parse it ( try JSON.parse )
JSON.stringify() does exactly what it sounds like. It turns the javascript object into a string. So when you do arr[0] you are getting the first letter in the string. You need to turn it back into a javascript object if you want to get the actual values.

.find('.foo').text() as array [duplicate]

This question already has answers here:
Get array of text values using selector instead of iterating?
(7 answers)
Closed 9 years ago.
I have html with multiple things classed .text. I the perform
console.log($(whatever).find('.foo').text());
The result is a textstring with all the contents in it. Can I save it to an array instead somehow?
You can use the map method to get this done
var textArray = $(whatever).find('.foo').map(function() {
return $(this).text();
}).get();
This will get you an array.. If you want to display it as a string then just use join along with it.
Check Fiddle
var arr = [];
$(whatever).find('.foo').each(function() {
arr.push($(this).text());
});

Categories

Resources