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'
6 Réponses :
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);
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);
J'ai implémenté votre solution et cela fonctionne très bien. Merci
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);
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));
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:
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
}
)
// ...
}
)
return {
...childInCurrentIteration,
link: childInCurrentIteration.link.map(otherFunctionTransformingEachChild)
}
map return {
...childInCurrentIteration
}
{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)
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'))
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);