key-value pair undefined in javascript - javascript

For some reason I have a string like this:
"id: 123, title: something, category: science, ... "
To make a javascript object containing the key-value pairs I wrote the following method:
function stringToMap(stringToCut){
var map = {};
var listOfPairs = stringToCut.split(",");
for(var i = 0; i < listOfPairs.length; i++){
var pair = listOfPairs[i].split(":");
map[pair[0]] = pair[1];
}
return map;
}
it's important to access it with dot, not with [] brackets.
In chrome debug mode I see the expected object, but when I want to access one of it's element, like:
console.log(obj.title);
I get undefined...
What Am I doing wrong?

It's because there's a space in your key name:
console.log(obj[" title"]); // "something"
To fix this, change your first split to split on ", " instead of just ",":
var listOfPairs = stringToCut.split(", ");
JSFiddle demo.
As a further fix, you'll also want to change your second split to split on ": " rather than just ":", otherwise all your values will begin with spaces.
var pair = listOfPairs[i].split(": ");

Related

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

Getting the name of an array under another array

Suppose I have this code:
var simple = {
Cicatrix: ["Rock", "Bottom", "Stunner"],
Yen_Sid: ["Pirate", "Heroes", "Power"],
};
Calling Rock, Bottom, Stunner and etc. is easy.
document.write(simple.Cicatrix[0]);
However, what if i wanted to get the word Cicatrix and Yen_Sid? I want them to be called because I am going to use them as menus.
Also is it possible to have spaces in array names? Like Yen_Sid turns to Yen Sid. Or should I do a .replace?
Yes, you can have spaces in property names, you just need a delimiter around it:
var simple = {
Cicatrix: ["Rock", "Bottom", "Stunner"],
"Yen Sid": ["Pirate", "Heroes", "Power"],
};
However, if you want to loop out the items in a specific order, then you don't want them as object properties, you want them as items in an array. The properties in an object doesn't have a specific order, so when you loop out properties the order depends on the implementation in the browser, and different browsers will give you the properties in different order.
var simple = [
{ name: "Cicatrix", items: ["Rock", "Bottom", "Stunner"] },
{ name: "Yen Sid", items: ["Pirate", "Heroes", "Power"] }
];
To loop through the items and subitems you just need a nested loop:
for (var i = 0; i < simple.length; i++) {
// menu item is in simple[i].name
// subitems are in simple[i].items:
for (var j = 0; j < simple[i].items.length; j++) {
// subitem is in simple[i].items[j]
}
}
Simply use a for loop to go over simple with a replace.
var simple = {
Cicatrix: ["Rock", "Bottom", "Stunner"],
Yen_Sid: ["Pirate", "Heroes", "Power"],
};
for(x in simple)
console.log(x.replace('_',' '));
This allows you to iterate over an object's properties
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
It is not possible to have whitespace as you suggest in object notation property names unless you use double quotes like
obj = {"prop 1": [1,2,3]}
var t = obj["prop 1"]
For your first question, getting keys as strings is possible using Object.keys() method. I am not going to write examples here since the documentation I provided earlier has plenty of snippets that shows you how to use it. Other solution would be to use for loop to loop over the keys as Matthew Christianson pointed out in other answer.
And yes, you can have keys that are named with space, but when you're calling them be sure to do it using object.[property] notation, as in:
var x = {
"a b c" : 1234
}
console.log(x["a b c"]); // will log "1234" to Console!
I wouldn't suggest you using names with spaces since your code gets a bit messy using bracket notation, in my opinion. But you can make another object whose keys are keys from your primary object, and values are correctly spelled names, as in:
var names = {
YenSid : "Yen Sid",
SomeName : "Some name",
SomeOtherName : "Some other name"
}
var properObject = {
YenSid = 123,
SomeName = 456,
SomeOtherName = 789
}
And to get a correct name just use names.YenSid
Try this, its an example of how to print out the array to a string.
var text = "";
$.each(simple, function(k) {
text = text + "// " + k + " contains: ";
for ( var i = 0, l = $(this).length; i < l; i++ ) {
text = text + $(this)[i] + ", ";
}
});
console.log(text);

JavaScript: Push to Array with unknown key names

I have a small program that returns JSON which I'm then interrogating before pushing it into an array.
An example of the data is as follows:
id=1|owner=Vina San Pedro|brandName=1865 Chilean Wine|variantName=1865 Chilean Wine|quality=Standard|minorRegionName=Nordic Countries|vol02=0|vol07=0|vol08=4.25|vol09=4.25|vol10=0|
I can iterate the above string, pushing the values into the array, but how can I 'name' the key in the array based on the field name from JSON, considering that items such as "Vol02", "Vol07" may be marked as "val02", "val07", or "minorRegionName" can in some cases by "majorRegionName".
edit
var finalSplit = brandDataRow.split('|');
$.each(finalSplit, function (x, y) {
var v = y.split('=');
$.each(v, function (m, n) {
formattedBrandData.push({ m: m }, { n: n });
});
});
In the above example, if my | delimiterred string contains "Owner=??????|Value=????????|Brand=???????" then when I push this into an array, I want the keys to be "Owner", "Value" and "Brand".
BUT, I don't know the key names until after I've returned the data, so sometimes the | delimitered string could be "Owner=??????|Line=???????|Region=??????"
Try this:
var data = "id=1|owner=Vina San Pedro|brandName=1865 Chilean Wine|variantName=1865 Chilean Wine|quality=Standard|minorRegionName=Nordic Countries|vol02=0|vol07=0|vol08=4.25|vol09=4.25|vol10=0|";
var keyVal = data.split("|");
var res = {};
for(var i =0; i< keyVal.length; i++) {
var tmp = keyVal[i].split("=")
res[tmp[0]] = tmp[1];
}
console.log(res);
Yes, it will return an object, but array can contain only numerical indexes. And in most cases you can work with object the same way as with array. Besides, see no reason to use $.each for such a simple task. Just an additional code to execute.
JSFiddle demo - see console output
First off: you're not looking for an array, but an object. JS Arrays are actually objects in drag, but that's not the point; JS doesn't have associative arrays, only objects. But to answer your question: IMO, the easiest (and, I suspect, quickest) way you can convert your string to an object is by converting it to valid JSON:
var str = 'id=1|owner=Vina San Pedro|brandName=1865 Chilean Wine|variantName=1865 Chilean Wine|quality=Standard|minorRegionName=Nordic Countries|vol02=0|vol07=0|vol08=4.25|vol09=4.25|vol10=0|';
var obj = JSON.parse('{"'+str.substring(0,str.length-1).replace(/(=|\|)/g,function(s1,s2)
{
return '"'+(s2 === '=' ? ':' : ',')+'"';
})+'"}');
This is the dense version, if we break it down:
str.substring(0,str.length-1);//leave out trailing pipe (|)
//if the pipe is not always there:
str = str.substr(-1) === '|' ? str.substring(0,str.length-1) : str;
Then replace all = and |:
str = str.replace(/(=|\|)/g,function(s1,s2)
{//s1 will be the entire matched substring, s2 the first group, not required in this case, but just so you know
return '"'+(s2 === '=' ? ':' : ',') + '"';
});//pipes become comma's, = becomes colon
We're almost there now, the returned string will be id":"1","owner":"Vina San Pedro","brandName":"1865 Chilean Wine","variantName":"1865 Chilean Wine","quality":"Standard","minorRegionName":"Nordic Countries","vol02":"0","vol07":"0","vol08":"4.25","vol09":"4.25","vol10":"0. As you can see, all we need to add are the opening and closing curly's, and a double quote at the beginning and end of the string, and we end up with valid JSON:
var obj = JSON.parse('{"'+str+'"}');//returns object
//is the same as:
obj = { brandName: "1865 Chilean Wine",
id: "1",
minorRegionName: "Nordic Countries",
owner: "Vina San Pedro",
quality: "Standard",
variantName: "1865 Chilean Wine",
vol02: "0",
vol07: "0",
vol08: "4.25",
vol09: "4.25",
vol10: "0"};
From then on:
console.log(obj.id);//logs 1
console.log(obj.owner);//logs 'Vina San Pedro'
console.log(obj['brandName']);//string access: logs "1865 Chilean Wine"
//etc...
This code is tested and working
You can use string to name the key.
Eg.
var sample = new Array();
sample["bob"] = 123;
sample.bob; //returns 123
Hope it helps.

Javascript/Jquery Convert string to array

i have a string
var traingIds = "${triningIdArray}"; // ${triningIdArray} this value getting from server
alert(traingIds) // alerts [1,2]
var type = typeof(traingIds )
alert(type) // // alerts String
now i want to convert this to array so that i can iterate
i tried
var trainindIdArray = traingIds.split(',');
$.each(trainindIdArray, function(index, value) {
alert(index + ': ' + value); // alerts 0:[1 , and 1:2]
});
how to resolve this?
Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.
var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]
//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [ and ] and then split the string
Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
var traingIds = ${triningIdArray};
not
var traingIds = "${triningIdArray}";
check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
​for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}​

jQuery loop with an array error

i have this snippet. As a result i see an error: Invalid left-hand side in assignment.
var arr = [ "text1", "text2", "text3", "text4" ];
jQuery.each(arr, function(index, value) {
this = jQuery("#sc-dialog ."+value).val();
});
Does anyone can point me to how to fix this?
Thanks.
This is an UPDATE
I need that variable 'text' will have the numbers in the loop: text1, text2, text3... i have made it like this:
var arr = [ "1", "2", "3", "4" ];
jQuery.each(arr, function(index, value) {
var text + index = jQuery("#sc-dialog .text"+value).val();
});
But i got an error: Unexpected identifier. The problem is here: var text + index
Try like this:
jQuery.each(arr, function(index, value) {
arr[index] = jQuery("#sc-dialog ."+value).val();
});
Putting a + after your variable name is a syntax error in your var statement:
var text + index = jQuery("#sc-dialog .text"+value).val()
A valid variable declaration will be either variable name by itself:
var text;
Or the variable name with an assigned value:
var text = jQuery("#sc-dialog .text"+value).val();
The value being assigned can have a + or other operators in it:
var x = y + z - 5 * (a + b);
And in a single var statement you can declared multiple variables with or without values by separating them with commas:
var i, j = 0, k, text = jQuery("#sc-dialog .text"+value).val(), x = 12 + 4;
An array of numbers that follow a simple pattern (in this case array element index plus 1) is kind of pointless when you can achieve the same thing with a standard for loop. EDIT: from your comment it seems like you don't want to process the values within the loop, you want to store the values for later use. You mention wanting text1, text2, etc., but if you need to reference them individually it sounds like your various textareas aren't really a group and it doesn't make sense to process them in a loop at all. But if you insist then you should store the values in an array:
var i,
text = [];
for (i = 1; i <=4; i++) {
text[i] = jQuery("#sc-dialog .text"+i).val();
}
// later in your code
// text[1] is first value,
// text[2] is second value, etc
Note that JS array indexes are zero-based, and array .length is one more than the highest index, but your field numbering starts at 1 - keep that in mind if you later loop over the text array.
You can't use 'this' as a variable name. try something like:
var arr = [ "text1", "text2", "text3", "text4" ];
jQuery.each(arr, function(index, value) {
var dialogValue = jQuery("#sc-dialog ."+value).val();
});

Categories

Resources