Way to get assign the Object in jquery - javascript

I have Object obj in jquery
var obj = {};
I have the string str
var str = "passengerDetails[0].photo";
Now I am assigning this str as key in Object obj like below
obj = {str : "xx"} //means {"passengerDetails[0].photo" : xx} should come
But it is assigning as obj ={"str":"xx"};
What is the simple solution to this jquery Object code?

Try ,
var obj = {};
var str = "passengerDetails[0].photo";
obj[str] = "xx"; //it should work
console.log(obj); //Outputs --> Object { passengerDetails[0].photo="xx"}

var obj = {};
var str = "passengerDetails[0].photo";
obj[str] = "xx"; //it should work
console.log(obj); //Outputs --> Object { passengerDetails[0].photo="xx"}
//Thanks a lot to CodingAnt and this answer working like a boss

Related

How to make object of keys and values based on a string?

I have a following string:
var str = "name=test1^assigned_to=12345678901112131415161718991234^business_service=99945678901112131415161718991211^EQ";
var obj = { name: 'test1',
assigned_to: '12345678901112131415161718991234',
business_service: '99945678901112131415161718991211'
};
and would like to create object of specific keys and values from that string as is in my example, has anyone achieved similar thing? How?
let str = "name=test1^assigned_to=12345678901112131415161718991234^business_service=99945678901112131415161718991211^EQ";
let obj = {}
str.split('^').forEach(e => {
let x = e.split('=');
if (x[1])
obj[x[0]] = x[1]
});
console.log(obj);
You can remove if (x[1]) condition;

Converting a String to a Javascript Object

Am trying to convert the following string value into a javascript object
Example
string="name=usernamex&gender=boy&age=10&version_obj=1"
into
var user={ name:'username', gender:'boy',age:10,version_obj=1}
Can someone help me out
Looks like you want the querystring module: http://nodejs.org/api/querystring.html
querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// { foo: 'bar', baz: ['qux', 'quux'], corge: '' }
with pure javascript..
var str="name=usernamex&gender=boy&age=10&version_obj=1";
var array = str.split('&');
var obj = {};
array.forEach(function(value){
var x = value.split('=');
obj[x[0]] = decodeURIComponent(x[1]);
});
console.log(obj);
If you don't want to use a module:
var strArr = string.split("&");
var user = {}, i = 0, n;
while(i<strArr.length) {
n = strArr[i].split("=");
if(n.length == 2)
user[decodeURIComponent(n[0])]
= decodeURIComponent(n[1]);
i++;
}

how to convert json objects sepeted by comma into object

i have a string of 2 json object like this:
var param = '{"key1":"value1","key2":"value2"},{"key3":"value3"}';
how can i separate into 2 object like this in javascript..
var objA = {"key1":"value1","key2":"value2"};
var objB = {"key3":"value3"};
As simple as this - make an array from this objects
var param = '{"key1":"value1","key2":"value2"},{"key3":"value3"}';
var obj = JSON.parse('[' + param + ']');
var objA = obj[0];
var objB = obj[1];
Like this
var data = JSON.parse("[" + param "]");
objA = data[0];
objB = data[1];
You JSON string is wrong. Change your code to
var param = '[{"key1":"value1","key2":"value2"},{"key3":"value3"}]';
var jsonArr = JSON.parse(param);
for(var i in jsonArr) {
var jsonObj = jsonArr[i];
// jsonObj is your required object
}
See this FIDDLE here.
You could also do it with objects like this;
var param = '{"objA": {"key1": "value1","key2": "value2"}, "objB": {"key3": "value3"}}',
obj = JSON.parse(param),
objA = obj.objA,
objB = obj.objB;
console.log([obj, objA, objB]);
jsfiddle

Push an associative item into an array in JavaScript

How can I correct the following code?
var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);
JSFiddle
To make something like associative array in JavaScript you have to use objects.
​
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
DEMO: http://jsfiddle.net/bz8pK/1/
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);​
To get value you can use now different ways:
console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​
JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
They are simply called objects.
Another method for creating a JavaScript associative array
First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];
If you came to this question searching for a way to push to the end of an associative array while preserving the order, like a proper stack, this method should work. Although the output is different than the original question, it is still possible to iterate through.
// Order of entry altered
let obj = {}; // will create an object
let name = "4 name";
let val = 4;
obj[val] = name;
name = "7 name";
val = 7;
obj[val] = name;
name = "2 name";
val = 2;
obj[val] = name;
console.log(obj);
// Order of entry maintained for future iteration
obj = []; // will create an array
name = "4 name";
val = 4;
obj.push({[val]:name}); // will push the object to the array
name = "7 name";
val = 7;
obj.push({[val]:name});
name = "2 name";
val = 2;
obj.push({[val]:name});
console.log(obj);

how can I declare a value deep in an object tree using variable properties in javascript

I am trying to have a javascript object tree behave like a php associative array in the following way.
var key1 = 'a';
var key2 = 'b';
var key3 = 'c';
var obj[key1][key2][key3] = 'd';
However, in javascript I believe you need to define each property/object pair individually, forming deeper leaves. Something like:
var obj[key1] = {};
var obj[key1][key2] = {};
...
Is there a way to simplify or shorten this script?
Thanks
I don't know if there's a "natural" way to do it, but you could do it like this:
function phpLike(){};
phpLike.prototype.set = function ()
{
var l = arguments.length;
if (l<2) return;
var o = this;
for (var i=0; i<l-2; i++)
{
if (o[arguments[i]] === undefined) o[arguments[i]] = {};
o = o[arguments[i]];
}
o[arguments[l-2]] = arguments[l-1];
}
// Test
var key1 = 'a';
var key2 = 'b';
var key3 = 'c';
var obj = new phpLike();
obj.set(key1, key2, key3, 'd');
alert(obj[key1][key2][key3]);
function setPropertyByKeyPath(obj, path, val) {
var key;
while (path.length > 1) {
key = path.shift();
obj[key] = typeof obj[key] === "object" ? obj[key] : {};
obj = obj[key];
}
obj[path.shift()] = val;
}
var o = {};
setPropertyByKeyPath(o, ['foo', 'bar'], 5);
alert(o.foo.bar)
Not directly, as far as I know, but how about using a little helper function?
function kv1(k, v) {
var o = { };
o[k] = v;
return o;
}
var obj = kv1(key1, kv1(key2, kv1(key3, 'd')));
I just thought of an answer inspired by Will's post: Construct a json string and then eval().
var obj = eval("{" + key1 + ": {... }};");
This kind of fulfils my search for a more concise way of declaring an object tree and deep leaf. But, it is ugly, confusing and I would avoid it like the plague.
var obj = { key1: { key2: { key3: 'd' } } }
This syntax is the basis of the format known as JSON: http://en.wikipedia.org/wiki/JSON

Categories

Resources