Estoy tratando de convertir la siguiente matriz en un objeto:
var arr = [ 'car.name', 'car.age', 'car.event.id', 'zz.yy.dd.aa', 'aa.yy.zz.dd.kk' ];Entonces se verá así:
var targetObject = { car: { name: '', age: '', event: { id: '' } } , zz: { yy: { dd: { aa: '' } } }, aa: { yy: { zz: { dd: { kk: '', } } } } }Este es mi código:
targetObject = {} function arrayToObject(arr){ //iterate through array and split into items for (var i = 0; i < arr.length; ++i){ var item = arr[i].split("."); //iterate through item that has just been splitted for (var u = 0; u < item.length; ++u){ //if item is not in targetobject create new object if(!(item[0] in targetObject)){ targetObject[item[0]] = {} } else { //else go into the object and add the item/property to the existing object targetObject[item[0]][item[u]] = {} } } } console.log(targetObject); } arrayToObject(arr);Sale solo en el segundo nivel y no puedo descifrar cómo hacerlo con los varios niveles. Sé que el código es de la vieja escuela, por lo que también me gustaría saber cómo se puede hacer esto más fácilmente.
Puede usar forEach para recorrer la matriz y luego split con reduce para construir un objeto anidado.
var arr = [ 'car.name', 'car.age', 'car.event.id', 'zz.yy.dd.aa', 'aa.yy.zz.dd.kk' ]; const result = {} arr.forEach(str => { str.split('.').reduce((r, e, i, a) => { return r[e] = (r[e] || (a[i + 1] ? {} : '')) }, result) }) console.log(result) O con su enfoque con bucles for , solo necesita mantener alguna referencia y actualizar el objeto anidado actual, para que pueda hacerlo así.
var arr = [ 'car.name', 'car.age', 'car.event.id', 'zz.yy.dd.aa', 'aa.yy.zz.dd.kk' ]; const targetObject = {} let ref = targetObject; function arrayToObject(arr) { //iterate through array and split into items for (var i = 0; i < arr.length; ++i) { var item = arr[i].split("."); //iterate through item that has just been splitted for (var u = 0; u < item.length; ++u) { const last = u == item.length - 1 const str = item[u] if (!ref[str]) { ref[str] = (last ? '' : {}) } ref = ref[str] if (last) { ref = targetObject; } } } } arrayToObject(arr); console.log(targetObject)