ways to convert array to object in my case - javascript

I face this problem a lots and I tired of writing conversion function
I can do
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
but is there short-cut for that? my case as below :
angular.forEach($scope.data, function(item){
if(thread.checked === true){
var links = item.url;
chrome.tabs.create(links, function(tab) {
});
}
});
I'm using chrome API where links is obj :
chrome.tabs.create(obj, function(tab) {
});

In an ES5 browser you can do:
var obj = {};
[0,1,2].forEach(function(v, i){obj[i] = v});
or
[0,1,2].forEach(function(v, i, arr){this[i] = v}, obj);
As a function:
function toObj(arr) {
var obj = {};
arr.forEach(function(v, i){obj[i] = v});
return obj;
}
If the object passed in may not be an array but an object with properties 0 to n, then:
function toObj(arr) {
var obj = {};
[].forEach.call(arr, function(v, i){obj[i] = v});
return obj;
}

Related

JavaScript: Convert dot notation string to array [duplicate]

I'm trying to create a JS object dynamically providing a key and a value. The key is in dot notation, so if a string like car.model.color is provided the generated object would be:
{
car: {
model: {
color: value;
}
}
}
The problem has a trivial solution if the key provided is a simple property, but i'm struggling to make it work for composed keys.
My code:
function (key, value) {
var object = {};
var arr = key.split('.');
for(var i = 0; i < arr.length; i++) {
object = object[arr[i]] = {};
}
object[arr[arr.length-1]] = value;
return object;
}
your slightly modified code
function f(key, value) {
var result = object = {};
var arr = key.split('.');
for(var i = 0; i < arr.length-1; i++) {
object = object[arr[i]] = {};
}
object[arr[arr.length-1]] = value;
return result;
}
In the loop you should set all of the props but the last one.
Next set the final property and all set.
If you're using lodash you could use _.set(object, path, value)
const obj = {}
_.set(obj, "car.model.color", "my value")
console.log(obj)
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
Use namespace pattern, like the one Addy Osmani shows: http://addyosmani.com/blog/essential-js-namespacing/
Here's the code, pasted for convenience, all credit goes to Addy:
// top-level namespace being assigned an object literal
var myApp = myApp || {};
// a convenience function for parsing string namespaces and
// automatically generating nested namespaces
function extend( ns, ns_string ) {
var parts = ns_string.split('.'),
parent = ns,
pl, i;
if (parts[0] == "myApp") {
parts = parts.slice(1);
}
pl = parts.length;
for (i = 0; i < pl; i++) {
//create a property if it doesnt exist
if (typeof parent[parts[i]] == 'undefined') {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
}
// sample usage:
// extend myApp with a deeply nested namespace
var mod = extend(myApp, 'myApp.modules.module2');
function strToObj(str, val) {
var i, obj = {}, strarr = str.split(".");
var x = obj;
for(i=0;i<strarr.length-1;i++) {
x = x[strarr[i]] = {};
}
x[strarr[i]] = val;
return obj;
}
usage: console.log(strToObj("car.model.color","value"));
I would use a recursive method.
var createObject = function(key, value) {
var obj = {};
var parts = key.split('.');
if(parts.length == 1) {
obj[parts[0]] = value;
} else if(parts.length > 1) {
// concat all but the first part of the key
var remainingParts = parts.slice(1,parts.length).join('.');
obj[parts[0]] = createObject(remainingParts, value);
}
return obj;
};
var simple = createObject('simple', 'value1');
var complex = createObject('more.complex.test', 'value2');
console.log(simple);
console.log(complex);
(check the console for the output)
Here's a recursive approach to the problem:
const strToObj = (parts, val) => {
if (!Array.isArray(parts)) {
parts = parts.split(".");
}
if (!parts.length) {
return val;
}
return {
[parts.shift()]: strToObj(parts, val)
};
}

Create nested object dynamically with forEach

I have an 'path' string: 'profile.name.en';
I want to use this to create an object dynamically. I'm using this function and its working:
function set(obj, path, value) {
var schema = obj; // a moving reference to internal objects within obj
var arr = path.split('.');
var len = arr.length;
for(var i = 0; i < len-1; i++) {
var elem = arr[i];
if( !schema[elem] ) schema[elem] = {};
schema = schema[elem];
}
schema[arr[len-1]] = value;
return schema;
}
Use it like this:
var a = {};
var path = 'profile.name.en';
var profileName = 'OleFrank';
var o = set(a, path, profileName);
// result
{
profile: {
name: {
en: 'OleFrank'
}
}
}
I tried to refactor to using forEach instead of for-loop, but then it's not working anymore. Why is this??
You could use Array#reduce, because this returns the object you need, without keeping a reference outside.
function set(object, path, value) {
var keys = path.split('.'),
last = keys.pop();
keys.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var a = {},
path = 'profile.name.en',
profileName = 'OleFrank';
set(a, path, profileName); // no need of an assignment, because of
// call by reference with an object
console.log(a);
Version with Array#forEach
function set(object, path, value) {
var keys = path.split('.'),
last = keys.pop();
keys.forEach(function (k) {
object[k] = object[k] || {};
object = object[k];
});
object[last] = value;
}
var a = {},
path = 'profile.name.en',
profileName = 'OleFrank';
set(a, path, profileName);
console.log(a);

convert array to object javascript

I have the following array:
["recordList", "userList", "lastChanged"]
And I want something like this:
lastChangedValue = "231231443234";
var object = {};
object = {
recordList: {
userList: {
lastChanged: lastChangedValue
}
}
}
How I can do this?
Thanks in advance.
Try this:
var array = ["recordList", "userList", "lastChanged"];
var value = "231231443234";
function arrayToObject(array, object, value) {
var ref = object;
for (var i=0; i<array.length-1; ++i) {
if (!ref[array[i]]) {
ref[array[i]] = {};
}
ref = ref[array[i]]
}
ref[array[array.length-1]] = value;
return object;
}
alert(JSON.stringify(arrayToObject(array, {}, value)));
You can iterate through property names and create one nested level of new object in each iteration:
var props = ["recordList", "userList", "lastChanged"];
var lastChangedValue = "231231443234";
var obj = {}
var nested = obj;
props.forEach(function(o, i) {
nested[o] = i === props.length - 1 ? lastChangedValue : {};
nested = nested[o];
});
console.log(obj);
There are probably a bunch of ways to do it, one way is with reduce
var keys = ["recordList", "userList", "lastChanged"];
var temp = keys.slice().reverse(),
lastChangedValue = "231231443234";
var result = temp.reduce( function (obj, val, ind, arr) {
if (ind===0) {
obj[val] = lastChangedValue;
return obj;
} else {
var x = {};
x[val] = obj;
return x;
}
}, {});
console.log(result);
Solving with recursion
var fields = ["recordList", "userList", "lastChanged"];
lastChangedValue = "231231443234";
var object = {};
(function addFields(o, i, v) {
if (i == fields.length - 1) {
o[fields[i]] = v;
return;
}
o[fields[i]] = {};
addFields(o[fields[i]], ++i, v)
})(object, 0, lastChangedValue);
alert(JSON.stringify(object));

Convert an array into an object in JavaScript

Exists a more elegant way to create an object from an array than this one?
var createObject = function(){
var myArray= generateArray();
var myObject = {
question : myArray[0],
answerA : myArray[1],
answerB : myArray[2],
answerC : myArray[3],
answerD : myArray[4]
};
return myObject;
}
What's your background? Python?
var values = generateArray();
var obj = {};
["question", "answerA", "answerB", "answerC", "answerD"].forEach(function(item, idx) {
obj[item] = values[idx];
});
return obj;
You could define an attribute map:
var createObject = function(){
// The map should have the attribute names set in order defined in `myArray`
var map = ["question", "answerA", "answerB", "answerC", "answerD"]
var myArray = generateArray();
var myObject = {};
for(var i in map)
myObject[map[i]] = myArray[i];
return myObject;
}
Try this to go beyond 'A', 'B', 'C', 'D':
function arrayToObject ( array ) {
return array.reduce(
function ( object, cell, index ) {
if (index > 0) object['answer' + String.fromCharCode(64 + index)] = cell;
else object['question'] = cell;
return object;
}, {}
);
}
If you would like to have a function that takes an array as an argument, and returns an object, this is how I would do it:
var toObject = function(arr) {
var newObj = {};
for(var i = 0; i < arr.length; i++) {
newObj[i] = arr[i];
}
return newObj;
};
However, keep in mind that Javascript arrays are simply objects with more methods available to them such as push(), pop(), and the length property.
Hope this helps!

Javascript nested objects from string

I've got an empty object and a string:
var obj = {};
var str = "a.b.c";
Is there a way I can turn this into
obj = { a: { b: { c: { } } } }
I can't quite wrap my head around this one and I'm not even sure if it would be possible.
var obj = {};
var str = "a.b.c";
var arr = str.split('.');
var tmp = obj;
for (var i=0,n=arr.length; i<n; i++){
tmp[arr[i]]={};
tmp = tmp[arr[i]];
}
ES6:
let str = "a.b.c",
arr = str.split('.'),
obj, o = obj = {};
arr.forEach(key=>{o=o[key]={}});
console.log(obj);
ES6/Reduced (array storage unnecessary):
let str = "a.b.c", obj, o = obj = {};
str.split('.').forEach(key=>o=o[key]={});
console.log(obj);
ES6/Array.prototype.reduce:
let str = "a.b.c", last;
let obj = str.split('.').reduce((o, val) => {
if (typeof last == 'object')
last = last[val] = {};
else
last = o[val] = {};
return o;
}, {});
console.log(obj);
This is from the yui2 yahoo.js file.
YAHOO.namespace = function() {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
d=(""+a[i]).split(".");
o=YAHOO;
// YAHOO is implied, so it is ignored if it is included
for (j=(d[0] == "YAHOO") ? 1 : 0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
};
See the source for documentation.
https://github.com/yui/yui2/blob/master/src/yahoo/js/YAHOO.js
This recursive function returns you the string representation of the desired object
//Usage: getObjectAsString('a.b.c'.split(/\./))
function getObjectAsString (array){
return !array.length ? '{}'
: '{"' + array[0] + '":' + getObjectAsString (array.slice(1)) + '}';
}
Now you can convert the output of getObjectAsString into object using
JSON.parse(getObjectAsString('a.b.c'.split(/\./)))
EDIT: Removed 'Input as String' version as it works only for single letter subparts in the namespace such as the one given in the question (a.b.c) which is generally not the case.
Here you go:
var string = "a.b.c",
array = string.split('.');
JSON.parse("{\"" + array.join('": {\"') + "\": {" +array.map(function () {return '}'}).join('') + "}")
Example
Here's my take on it:
function ensureKeys(str, obj) {
for(var parts = str.split('.'), i=0, l=parts.length, cache=obj; i<l; i++) {
if(!cache[parts[i]]) {
cache[parts[i]] = {};
}
cache = cache[parts[i]];
}
return obj;
}
var obj = {};
ensureKeys('a.b.c', obj);
// obj = { a: { b: { c: {} } } }

Categories

Resources