tengo los siguientes datos:
const data = [ { id: 1, metadata: { attributes: [ { type: 'background', value: 'red', }, { type: 'background', value: 'blue', }, { type: 'size', value: 'small', }, ], }, }, { id: 2, metadata: { attributes: [ { type: 'background', value: 'red', }, { type: 'background', value: 'blue', }, ], }, }, { id: 3, metadata: { attributes: [ { type: 'background', value: 'red', }, { type: 'background', value: 'green', }, { type: 'size', value: 'small', }, ], }, }, ];Para cada objeto en la matriz de atributos, tengo que crear un nuevo objeto basado en la propiedad de tipo. La propiedad de tipo será una clave en este nuevo objeto y el valor será otra propiedad anidada dentro. El valor de la propiedad anidada será una matriz que contiene todos los identificadores correspondientes. Entonces, tengo que lograr algo como esto como resultado final:
const desiredResult = { background: { red: [1, 2, 3], //these are ids blue: [1, 2], green: [3], }, size: { small: [1, 3], }, };Puede probar for each o for ... of en javascript. código limpio para principiantes como a continuación:
function process (data) { let result = {}; for (let datum of data) { for (let attribute of datum.metadata.attributes) { result[attribute.type] = result[attribute.type] || {}; result[attribute.type][attribute.value] = result[attribute.type][attribute.value] || []; result[attribute.type][attribute.value].push(datum.id); } } return result; } // const desiredResult = process(data);Otro enfoque muy parecido a los otros aquí, pero usando datos inmutables, incluso para el acumulador:
const extract = (xs) => xs .reduce ((a, {id, metadata: {attributes = []} = {}}) => attributes .reduce ((a, {type: t, value: v}) => ({...a, [t]: {... (a [t] || {}), [v]: [...((a [t] || {}) [v] || []), id]}}), a), {}) const data = [{id: 1, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "blue"}, {type: "size", value: "small"}]}}, {id: 2, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "blue"}]}}, {id: 3, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "green"}, {type: "size", value: "small"}]}}] console .log (extract (data)) .as-console-wrapper {max-height: 100% !important; top: 0}Esto funciona para muchos tamaños de datos, pero puede generar un problema de rendimiento si los datos son realmente grandes. Si lo hace, es posible que deba elegir un acumulador mutable en su lugar. Pero no me preocuparía a menos que esta función muestre ser un cuello de botella en su aplicación.