I want to convert a REST style url into a javascript literal, like this:
from:
var url = "/a/b/c/d";
to:
var obj = {
a:{
b:{
c:{
d:{}
}
}
}
};
How would you do this?
You can probably condense it but here's a solution :
var u = '/a/b/c/d';
var t = u.split('/');
var o = {};
for (var i=t.length; i-->1; ) {
var temp = o;
o = {};
o[t[i]] = temp;
}
The result is o.
My attempt:
var url = '/a/b/c/d';
var fun = function(a) {
var res = {};
res[a[0]] = a.length == 1 ? {} : fun(a.slice(1));
return res;
};
// obj has what you need
var obj = fun(url.split('/').slice(1));
// OTHER EXAMPLE
var t = ['that', 'is', 'so', 'fun'];
console.log(fun(t));
// above returns object: {that: { is: { so: { fun: {} }}}}
Related
I try to create an object with a value for the last key. I just have an Array with the keys and the value but dont know how it will be possible to create an object without use references in javascript.
As far as I know there isnt a way to create a reference of a variable in javascript.
This is what i have:
var value = 'test';
var keys = ['this', 'is', 'a', 'test'];
This is what i want:
myObject: {
this : {
is: {
a : {
test : 'test'
}
}
}
}
Any idea how i can do this the best way in JavaScript ?
How about this...
const value = 'test'
const keys = ['this', 'is', 'a', 'test']
const myObject = keys.reduceRight((p, c) => ({ [c]: p }), value)
console.info(myObject)
Or, if you're not a fan of object literal key shortcuts and arrow functions...
keys.reduceRight(function(p, c) {
var o = {};
o[c] = p;
return o;
}, value);
See Array.prototype.reduceRight() - Polyfill if you need IE <= 8 support.
With this:
var curObj = myObject = {};
for(var i=0; i<keys.length-1; i++)
curObj = curObj[keys[i]] = {};
curObj[value] = keys[i];
Outputs:
{
this : {
is: {
a : {
Test : 'test'
}
}
}
}
As opposed to the other answers, this outputs exactly what you asked for.
Cheers
var o={}, c=o;
var value = 'Test';
var keys = 'this is a test'.split(' ');
for (var i=0; i<keys.length-1; ++i) c = c[keys[i]] = {};
c[keys[i]] = value;
console.log(JSON.stringify(o));
// {"this":{"is":{"a":{"test":"Test"}}}}
If you want the output like
{
this : {
is: {
a : 'test'
}
}
}
Do the following
var keys = ['this', 'is', 'a', 'test'];
var output = keys.reduceRight((p,c)=>({[c]:p}))
console.log(output)
And the output will be like
{ this: { is: { a: 'test' } } }
Given the following string with key-value pairs, how would you write a generic function to map it to an object?
At the moment, I am just splitting by : and ; to get the relevant data, but it doesn't seem like a clean approach.
This my code at the moment:
var pd = `id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74`;
var tempPd = pd.split(';');
for (i = 1; i < tempPd.length; i++) {
var b = tempPd[i].split(':');
console.log(b[1]);
}
What about using reduce:
function objectify(str) {
return str.split(";").reduce(function (obj, item) {
var a = item.split(":");
obj[a[0]] = a[1];
return obj;
}, {});
}
var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74";
console.log(objectify(strObj));
or:
function objectify(str){
return str.split(";").reduce((obj,item)=>{
var a = item.split(":");
obj[a[0]]=a[1];
return obj;
},{});
}
var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74";
console.log(objectify(strObj));
I have an array like this: var arr = ["1:a", "2:b", "3:c"];
From above array I want an object: var obj = { "1": "a", "2": "b", "3": "c" }
I am doing:
var obj = {}
$.each(arr, function (i, value) {
var valueSplit = value.split(':');
// I don't know how to make the object
});
Edit:
My Question is mark as duplicate, while the question I asked is totally opposite of the marked duplicate question.
From your code, in place of the comment you could write
obj[valueSplit[0]] = valueSplit[1];
This could be written as a simple reduce:
var obj = arr.reduce(function(x,y) { return z = y.split(':'), x[z[0]]=z[1], x; }, {});
var arr = ["1:a", "2:b", "3:c"];
var obj = arr.reduce(function(x,y) { return z = y.split(':'), x[z[0]]=z[1], x; }, {});
document.write(JSON.stringify(obj));
Just add the assignment.
var obj = {}
$.each(arr, function (i, value) {
var valueSplit = value.split(':');
obj[valueSplit[0]] = valueSplit[1];
});
Simply try this
var arr = ["1:a", "2:b", "3:c"];
var map = {};
arr.forEach( function(val){
var keyVal = val.split( ":" );
map[ keyVal[ 0 ] ] = keyVal[ 1 ];
});
map is the object you are looking for.
DEMO
var arr = ["1:a", "2:b", "3:c"];
var map = {};
arr.forEach( function(val){
var keyVal = val.split( ":" );
map[ keyVal[ 0 ] ] = keyVal[ 1 ];
});
document.body.innerHTML += JSON.stringify( map, 0, 4 );
I'm starting with unit testing. I need to create some fake data to run the tests. So let's say inside a stubbed method I'm passing an obj as an argument and I do things with obj.obj1.obj2.data inside the function. Is there a way to set this fake object? So, given:
obj.obj1.obj2.data
It creates:
obj = {
obj1: {
obj2: {
data: 'whatever'}}}
So it would be at the end something like:
var obj = creator('obj.obj1.obj2.data', 20);
Assuming the string is only a set of objects (no arrays) this should be fairly straightforward. Just split the input string on . and then use a while loop to do the nesting.
function creator(str,val){
var tree = str.split('.');
var ret = {};
var cur = ret;
while(tree.length){
var name = tree.shift();
cur[name] = tree.length ? {} : val;
cur = cur[name];
}
return ret;
}
document.querySelector("#out").innerHTML = JSON.stringify(creator('obj.obj1.obj2.data',20));
<div id="out"></div>
Just in case anyone else in interested, I created a simple npm module with the function below (https://github.com/r01010010/zappy) check it out:
var objFrom = function(str, last_value){
var objs = str.split('.');
var r = {};
var last = r;
for(i=0; i < objs.length; i++) {
if(i !== objs.length - 1){
last = last[objs[i]] = {};
}else{
last[objs[i]] = last_value;
}
}
return r;
}
var obj = objFrom('obj1.obj2.data', 20);
console.log(obj.obj1.obj2.data);
I have a JS object:
var source = {};
source.quantity = 1;
source.text = 'test';
Now I JSON it:
var json = JSON.stringify(source);
json looks like this:
{"quantity":"1","text":"test"}
I would like it to be like this:
[{"quantity":"1"},{"text":"test"}]
Ho can I do this?
Get all the keys as an Array them map them to Objects as key-value pairs from source
JSON.stringify(
Object.keys(source)
.map(
function (e) {
var o = {};
o[e] = source[e];
return o;
}
)
); // "[{"quantity":1},{"text":"test"}]"
var json = JSON.stringify([
{quantity: "1"},
{text: "test"}
]);
I guess this is not possible but you can do this:
var source = {};
source.quantity = 1;
source.text = 'test';
var result = [];
for(var i in source) {
var obj = {};
obj[i] = source[i];
result.push(obj);
}
var json = JSON.stringify(result);
I hope this can help you.