1
votes

Javascript: créer un nouveau tableau d'objets (B) à partir d'un tableau d'objets (A) associés les uns aux autres

Depuis hier, je peux résoudre mon problème d'algorithme.

Je sais que le titre n'est pas clair, je vais donc essayer d'expliquer le plus clairement possible ce que j'ai en tête.

Ce que je veut est de construire à partir d'une table d'objets (A) une nouvelle table d'objets (B).

Le tableau d'objets (A) ressemble à ceci:

0 0 'REC-002'
0 1 'REC-003'
1 0 'REC-003'
2 0 'REC-001'
2 1 'REC-002'


0 commentaires

6 Réponses :


2
votes

Cela devrait fonctionner, veuillez confirmer si vous avez des problèmes et veuillez également modifier les noms des variables si besoin. (C'est une solution gourmande et je n'ai fait aucune optimisation)

 var d = [{
      id : "REC-001",
      text: "Facebook",
      link: ["REC-002", "REC-003"]
    },
    {
      id : "REC-002",
      text: "Instagram",
      link: ["REC-003"]
    },
    {
      id : "REC-003",
      text: "Snapshat",
      link: ["REC-001", "REC-002"]
    }];
    
    d.forEach(function(key){
      let newLink = [];
      key.link.forEach(function(linkData){
        d.forEach(function(obj){
          if(linkData === obj.id){
            newLink.push({key : obj.id, text : obj.text });
          }
        });
         key.link = newLink;
      });
    });
    
    console.log(d);


0 commentaires

2
votes

var arrA = [
  {
    id : "REC-001",
    text: "Facebook",
    link: ["REC-002", "REC-003"]
  },
  {
    id : "REC-002",
    text: "Instagram",
    link: ["REC-003"]
  },
  {
    id : "REC-003",
    text: "Snapshat",
    link: ["REC-001", "REC-002"]
  }
];

var arrB = arrA.map(itemA => ({
  id: itemA.id,
  text: itemA.text,
  link: itemA.link.map(l => {
    var foo = arrA.find(a => a.id === l);
    return {
      key: foo.id,
      text: foo.text
    };
  })
}));

console.log(arrB);


1 commentaires

J'ai implémenté votre solution et cela fonctionne très bien. Merci



2
votes

Vous pouvez d'abord obtenir l ' id , puis créer les tableaux imbriqués souhaités.

.as-console-wrapper { max-height: 100% !important; top: 0; }
var data = [{ id : "REC-001", text: "Facebook", link: ["REC-002", "REC-003"] }, { id : "REC-002", text: "Instagram", link: ["REC-003"] }, { id : "REC-003", text: "Snapshat", link: ["REC-001", "REC-002"] }],
    result = data.map(
        (m => o => (
            Object.assign(m[o.id] = m[o.id] || {}, { key: o.id, text: o.text }),
            { ...o, link: o.link.map(id => m[id] = m[id] || {}) })
        )
        ({})
    );
    
console.log(result);

Une autre approche avec une seule boucle avec une fermeture sur une table de hachage, qui recueille les valeurs plus tard.

.as-console-wrapper { max-height: 100% !important; top: 0; }
var data = [{ id : "REC-001", text: "Facebook", link: ["REC-002", "REC-003"] }, { id : "REC-002", text: "Instagram", link: ["REC-003"] }, { id : "REC-003", text: "Snapshat", link: ["REC-001", "REC-002"] }],
    ids = data.reduce((m, { id: key, text }) => m.set(key, { key, text }), new Map),
    result = data.map(o => ({ ...o, link: o.link.map(id => ids.get(id)) }));
    
console.log(result);


0 commentaires

1
votes

J'espère que cela vous aidera:

var ArrayA = [{
  id : "REC-001",
  text: "Facebook",
  link: ["REC-002", "REC-003"]
},
{
  id : "REC-002",
  text: "Instagram",
  link: ["REC-003"]
},
{
  id : "REC-003",
  text: "Snapshat",
  link: ["REC-001", "REC-002"]
}]

function getArrayB(array) {
  const formatLink = (key) => ({
    key,
    text: array.find(el => el.id === key).text
  });

  return array.map((item) => (
    item.link ? { ...item, link: item.link.map(formatLink) } : item
  ));
}

console.log(getArrayB(ArrayA));


0 commentaires

1
votes

Vous pouvez tirer parti de la puissance des méthodes de tableau map et find pour transformer le premier tableau au format souhaité.

Le Array.map est utilisée pour itérer et transformer chaque enfant du tableau d'origine.

La méthode Array.find est utilisée pour parcourir un autre (ou dans ce cas le même) tableau afin de trouver un enfant à l'intérieur.

return {
    key: linkObject.id,
    text: linkObject.text
}

Pour décortiquer ce qui se passe ici:

  1. Nous parcourons le arrayA Array et créons ainsi un nouveau tableau auquel chaque enfant est appliqué une transformation
mapArrayAChild.link.map(
    (mapLinkChild) => {
        const linkObject = arrayA.find(
            (linkKeyStringInCurrentIteration) => {
                return linkKeyStringInCurrentIteration.key === mapLinkChild
            }
        )
        // ...
    }
)
  1. À chaque itération, nous copions les propriétés de l'enfant de l'itération courante et le collons dans un nouvel objet (à l'aide de l'opérateur de diffusion)
return {
    ...childInCurrentIteration,
    link: childInCurrentIteration.link.map(otherFunctionTransformingEachChild)
}
  1. Nous réévaluons la propriété du lien avec un nouveau tableau qui est lui-même créé avec la méthode map
return {
    ...childInCurrentIteration
}
  1. Lors de la transformation de chaque enfant du tableau de liens, nous trouvons l'objet {id: "REC-002", text: "Instagram", ...} dans le tableau d'origine arrayA en utilisant la chaîne de clé de l'itération courante (par exemple "REC-002")
const arraB = arrayA.map(functionTransformingEachChild)
  1. Nous renvoyons un nouvel objet (au lieu de la chaîne qui faisait auparavant partie du tableau link ) et excluons les propriétés dont nous avons besoin.
const arrayA = [
	{
		id: 'REC-001',
		text: 'Facebook',
		link: ['REC-002', 'REC-003'],
	},
	{
		id: 'REC-002',
		text: 'Instagram',
		link: ['REC-003'],
	},
	{
		id: 'REC-003',
		text: 'Snapshat',
		link: ['REC-001', 'REC-002'],
	},
]

const arrayB = arrayA.map((mapArrayAChild) => {
	return {
		...mapArrayAChild, // copy properties from mapArrayAChild into the new object
		link: mapArrayAChild.link.map((mapLinkChild) => {
			const linkObject = arrayA.find((findLinkChild) => {
				return findLinkChild.id === mapLinkChild
			}) // Find which child of arrayA has the key corresponding to each child of the current's link array
			return {
				key: linkObject.id,
				text: linkObject.text,
			}
		}),
	}
})

console.log(JSON.stringify(arrayB, null, '\t'))


0 commentaires

2
votes

J'espère que cela résoudra votre problème:

let a = [{
  id : "REC-001",
  text: "Facebook",
  link: ["REC-002", "REC-003"]
},
{
  id : "REC-002",
  text: "Instagram",
  link: ["REC-003"]
},
{
  id : "REC-003",
  text: "Snapshat",
  link: ["REC-001", "REC-002"]
}];

let b = a.map( value => {
	return {
  	...value,
    link: [{key: value.link[0], text: 'Instagram'}, {key: value.link[1], text: 'Facebook'}]
  }
});

console.log(b);


0 commentaires