Estoy tratando de convertir una matriz 2d en un objeto json usando un mapa clave. El mapa clave parece
var keys = ['id', 'title', 'customer.id', 'customer.name', 'customer.phone.home', 'customer.phone.mobile' ];y los datos son
var data = [ [1, 'Task 1', 'C1', 'Customer 1', '999', '8888'], [2, 'Task 2', 'C2', 'Customer 2', '333', '5555'] ];La salida JSON debe ser
var output = [ { "id":1, "title":"Task 1", "customer":{ "id":"C1", "name":"Customer 1", "phone":{ "home":"999", "mobile":"8888" } } }, { "id":2, "title":"Task 2", "customer":{ "id":"C2", "name":"Customer 2", "phone":{ "home":"333", "mobile":"5555" } } } ];Estoy tratando de hacerlo pero no soy bueno aquí haciendo smerecursion, etc. ¿Alguien podría ayudarme, por favor?
function arrToJSON(headers, data){ var output = []; data.forEach(row, index){ var cObj = {}; headers.forEach(header, itemIndex){ var headerParts = header.split('.'); // NOt sure what to do here } } }Puede lograr fácilmente el resultado usando map y reduce en js.
createObj(acc, curr.split("."), 0, o[index]);es la función que se usa en recursividad y eso es lo que estás buscando.
Arguments
createObj( acc, // object in which you want to add value curr.split("."), // send path as an array 0, // current index in path, initially zero o[index] // value to be assigned ); var keys = [ "id", "title", "customer.id", "customer.name", "customer.phone.home", "customer.phone.mobile", ]; var data = [ [1, "Task 1", "C1", "Customer 1", "999", "8888"], [2, "Task 2", "C2", "Customer 2", "333", "5555"], ]; function createObj(obj, arr, index, value) { if (index === arr.length - 1) obj[arr[index]] = value; else { if (!obj[arr[index]]) obj[arr[index]] = {}; createObj(obj[arr[index]], arr, index + 1, value); } } const result = data.map((o) => { return keys.reduce((acc, curr, index) => { createObj(acc, curr.split("."), 0, o[index]); return acc; }, {}); }); console.log(result); /* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }Puede usar simplemente desestructurar y extender el operador con reducir.
var data = [ [1, "Task 1", "C1", "Customer 1", "999", "8888"], [2, "Task 2", "C2", "Customer 2", "333", "5555"], ]; const buildObject = (arr = []) => { return arr.reduce((acc, [id, title, cid, name, home, mobile]) => { const row = { id, title, customer: { id: cid, name, phone: { home, mobile } }, }; return acc.concat(row); }, []); }; console.log(buildObject(data));