slice string to pieces and store each in new array - javascript

Help needed.
I have string like ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"] (unlimited number of pairs)
I need to make an array with pair like wT (as index) and WLw as value, for the whole string (or simpler wT as index0, WLw as index 1 and so on)
I'm trying to do it in JavaScript but I just cant figure out how to accomplish this task.
Much much appreciate your help!!

You cannot have a string as an index in an array, what you want is an object.
All you need to do is loop over your array, split each value into 2 items (key and value) then add them to an object.
Example:
// output is an object
var output = {};
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
If you wanted an array of arrays, then its much the same process, just pushing each pair to the output object
// output is a multidimensional array
var output = [];
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
output.push(source[index].split("="));
}
Update If your source is actually a string and not an array then you will have to do a little more splitting to get it to work
var output = {};
var sourceText = "[\"wt=WLw\",\"V5=9jCs\",\"7W=71X\",\"rZ=HRP9\"]";
// i have escaped the quotes in the above line purely to make my example work!
var source = sourceText.replace(/[\[\]]/g,"").split(",");
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
Update 2
If your desired output is an array of arrays instead of an object containing key-value pairs then you will need to do something like #limelights answer.
Object with Key-Value pairs: var myObject = { "key1": "value1", "key2": "value2" };
with the above code you can access "value1" like this myObject["key1"] or myObject.key1
Array of Arrays: var myArray = [ [ "key1", "value1"] ,[ "key2", "value2" ] ];
with this code, you cannot access the data by "key" (without looping through the whole lot to find it first). in this form both "key1" and "value1" are actually values.
to get "value1" you would do myArray[0][1] or you could use an intermediary array to access the pair:
var pair = myArray[0];
> pair == ["key1", "value1"]
> pair[0] == "key1"
> pair[1] == "value1"
You can use a for each loop on both types of result
// array of arrays
var data = [ [ "hello", "world"], ["goodbye", "world"]];
data.forEach(function(item) {
console.log(item[0]+" "+item[1]);
});
> Hello World
> Goodbye World
// object (this one might not work very well though)
var data = { "hello": "world", "goodbye": "world" };
Object.keys(data).forEach(function(key) {
console.log(key+" "+data[key]);
});
> Hello World
> Goodbye World

The normal for loop would do perfectly here!
var list = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
var pairs = [];
for(var i = 0; i < list.length; i++){
pairs.push(list[i].split('='));
}
This would give you an array of pairs, which I assume you want.
Otherwise just get rid of the outer Array and do list[i].split('=');
If you want it put into an object ie. not an Array
var pairObject = {};
for(var i = 0; i < list.length; i++){
var pair = list[i].split('=');
pairObject[pair[0]] = pair[1];
}

Related

JS Array "Length" with non-consecutive index/key

How do I get the number of elements in an array with non-consecutive numbers as keys?
var array = [];
array[5] = "something";
array[10] = "nothing":
expected:
number of elements in array = 2
actual:
instead I get the last number used as the "length", 11
I can figure out the way to do this by iterating through each element. Is there is better way to do this?
You may count non empty cells:
array.filter(function(e){return e!==undefined}).length
Sounds like what you actually want is a dictionary, not an array. Have you considered that as an alternative data structure?
How to do associative array/hashing in JavaScript
var myArray = {};
myArray["5"] = "something";
myArray["10"] = "nothing";
And to get the length you would want to write a quick function like the one shown here:
Length of a JavaScript object
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var size = Object.size(myArray);
Or alternatively, even simpler (but not supported by IE8):
Object.keys(myArray).length
var array = [];
array[5] = "something";
array[10] = "nothing":
Your array in this case becomes :
[undefined,undefined,undefined,undefined,undefined,"something",undefined,undefined,undefined,undefined,"nothing"]
thats why the length is coming as 11. So ideally you should not set it like array[5] or array[10].
If you have variable keys, then you should use object
a = {};
a["5"] = "something";
a["10"] = "nothing"
Then a will look like {"5":"something","10":"nothing"}
Then you can calculate count as :
var elemCount = 0;
for(var key in a){
elemCount++;
}
Output:
elemCount = 2
Various other ways of getting length of keys in object:
How to efficiently count the number of keys/properties of an object in JavaScript?
var array= Array(5);
array[1] = 10;
array[3] = 3;
numberOfElements = 0;
for(var i =0; i<array.length; i++) {
if(array[i]!=undefined)
numberOfElements++;
}
alert(numberOfElements);

Javascript - nested loops and indexes

I am trying to build an array that should look like this :
[
[{"name":"Mercury","index":0}],
[{"name":"Mercury","index":1},{"name":"Venus","index":1}],
[{"name":"Mercury","index":2},{"name":"Venus","index":2},{"name":"Earth","index":2}],
...
]
Each element is the concatenation of the previous and a new object, and all the indexes get updated to the latest value (e.g. Mercury's index is 0, then 1, etc.).
I have tried to build this array using the following code :
var b = [];
var buffer = [];
var names = ["Mercury","Venus","Earth"]
for (k=0;k<3;k++){
// This array is necessary because with real data there are multiple elements for each k
var a = [{"name":names[k],"index":0}];
buffer = buffer.concat(a);
// This is where the index of all the elements currently in the
// buffer (should) get(s) updated to the current k
for (n=0;n<buffer.length;n++){
buffer[n].index = k;
}
// Add the buffer to the final array
b.push(buffer);
}
console.log(b);
The final array (b) printed out to the console has the right number of objects in each element, but all the indexes everywhere are equal to the last value of k (2).
I don't understand why this is happening, and don't know how to fix it.
This is happening because every object in the inner array is actually the exact same object as the one stored in the previous outer array's entries - you're only storing references to the object, not copies. When you update the index in the object you're updating it everywhere.
To resolve this, you need to create new objects in each inner iteration, or use an object copying function such as ES6's Object.assign, jQuery's $.extend or Underscore's _.clone.
Here's a version that uses the first approach, and also uses two nested .map calls to produce both the inner (variable length) arrays and the outer array:
var names = ["Mercury","Venus","Earth"];
var b = names.map(function(_, index, a) {
return a.slice(0, index + 1).map(function(name) {
return {name: name, index: index};
});
});
or in ES6:
var names = ["Mercury","Venus","Earth"];
var b = names.map((_, index, a) => a.slice(0, index + 1).map(name => ({name, index})));
Try this:
var names = ["Mercury","Venus","Earth"];
var result = [];
for (var i=0; i<names.length; i++){
var _temp = [];
for(var j=0; j<=i; j++){
_temp.push({
name: names[j],
index:i
});
}
result.push(_temp);
}
console.log(result)
try this simple script:
var b = [];
var names = ["Mercury","Venus","Earth"];
for(var pos = 0; pos < names.length; pos++) {
var current = [];
for(var x = 0; x < pos+1; x++) {
current.push({"name": names[x], "index": pos});
}
b.push(current);
}

get values in pairs from json array

Firstly, this is my json value i am getting from a php source:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
After that, I want to get and oid value along with the corresponding cid value for example, oid=2 and cid=107 at one go, oid=4 and cid=98 at another and so on. I am trying to use jquery, ajax for this.
I have tried many answers for this, like: Javascript: Getting all existing keys in a JSON array and loop and get key/value pair for JSON array using jQuery but they don't solve my problem.
I tried this:
for (var i = 0; i < L; i++) {
var obj = res[i];
for (var j in obj) {
alert(j);
}
but all this did was to return the key name, which again did not work on being used.
So, you have an array of key/value pairs. Loop the array, at each index, log each pair:
var obj = [{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}];
for (var i = 0; i < obj.length; i++) {
console.log("PAIR " + i + ": " + obj[i].oid);
console.log("PAIR " + i + ": " + obj[i].cid);
}
Demo: http://jsfiddle.net/sTSX2/
This is an array that you have //lets call it a:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
To get first element :
a[0] // this will give you first object i.e {"oid":"2","cid":"107"}
a[0]["oid"] // this will give you the value of the first object with the key "oid" i.e 2
and so on ...
Hope that helps.
`
Basically what you need is grouping of objects in the array with a property. Here I am giving two functions using which you can do this
// To map a property with other property in each object.
function mapProperties(array, property1, property2) {
var mapping = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
mapping[item[property1]] = mapping[item[property1]] || [];
mapping[item[property1]].push(item[property2]);
}
return mapping;
}
// To index the items based on one property.
function indexWithProperty(array, property) {
var indexing = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
indexing[item[property]] = indexing[item[property]] || [];
indexing[item[property]].push(item);
}
return indexing;
}
var data = [{
"oid": "2",
"cid": "107"
}, {
"oid": "4",
"cid": "98"
}, {
"oid": "4",
"cid": "99"
}];
var oidCidMapping = mapProperties(data, "oid", "cid");
console.log(oidCidMapping["2"]); // array of cids with oid "2"
var indexedByProperty = indexWithProperty(data, "oid");
console.log(indexedByProperty["4"]); // array of objects with cid "4"
May not be the exact solution you need, but I hope I am giving you the direction in which you have to proceed.
If you are willing to use other library you can achieve the same with underscorejs

JavaScript: convert objects to array of objects

I have thousands of legacy code that stores array information in a non array.
For example:
container.object1 = someobject;
container.object2 = someotherobject;
container.object3 = anotherone;
What I want to have is:
container.objects[1], container.objects[2], container.objects[3] etc.
The 'object' part of the name is constant. The number part is the position it should be in the array.
How do I do this?
Assuming that object1, object2, etc... are sequential (like an array), then you can just iterate through the container object and find all the sequential objectN properties that exist and add them to an array and stop the loop when one is missing.
container.objects = []; // init empty array
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
If you want the first item object1 to be in the [1] spot instead of the more typical [0] spot in the array, then you need to put an empty object into the array's zeroth slot to start with since your example doesn't have an object0 item.
container.objects = [{}]; // init array with first item empty as an empty object
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
An alternate way to do this is by using keys.
var unsorted = objectwithobjects;
var keys = Object.keys(unsorted);
var items = [];
for (var j=0; j < keys.length; j++) {
items[j] = unsorted[keys[j]];
}
You can add an if-statement to check if a key contains 'object' and only add an element to your entry in that case (if 'objectwithobjects' contains other keys you don't want).
That is pretty easy:
var c = { objects: [] };
for (var o in container) {
var n = o.match(/^object(\d+)$/);
if (n) c.objects[n[1]] = container[o];
}
Now c is your new container object, where c.object[1] == container.object1

array spliting based on our requirement

My array contains the values with comma as separator, like
array={raju,rani,raghu,siva,stephen,varam}.
But i want to convert into the below format like
array = {raju:rani raghu:siva atephen:varam}.
please give some logic to implement this one.
If you're starting with a string, you can split it upon comma:
var myString = 'raju,rani,raghu,siva,stephen,varam';
var array = myString.split(',');
Given that, you can do the following:
var array = [ 'raju', 'rani', 'raghu', 'siva', 'stephen', 'varam' ];
var result = {};
for(var i = 0; i < array.length; i+= 2) {
result[array[i]] = array[i+1];
}
... which gives the answer you've requested.
Keep in mind that if the array is not evenly divisible by 2, the value of the last item will be undefined.
This is how to convert array to key-value pair of objects (odd-index is key, even-index is value in the resulting key-value pairs)
var array = ['raju', 'rani', 'raghu','siva','stephen','varam'],
pairs = {};
for (var i = 0; i < array.length; i += 2) {
pairs [array[i]] = array[i + 1];
}

Categories

Resources