I'm learning by coding, here i have 'allNodes' an array of objects and 'currentNodee' object, i want to check if allNodes contains 'analyser' and 'id' which is equal to 'analyser' and 'id' of 'currentNodee' then take 'analyser' value and print it, but if for example 'allNodes' has same id but its analyser is 'undefined' then do not print anything.
what am i doing wrong here ? any idea is appreciated
const allNodes = [
{ analyser: undefined, id: 7 },
{ analyser: "abc", id: 6 },
];
const currentNodee = { analyser: "abc", id: 7 };
console.log(
allNodes.find((option: any) => {
option.id === currentNodee.id &&
option?.analyser === currentNodee?.analyser;
})
);
English is not my mother language so could be mistakes.
CodePudding user response:
const allNodes = [
{ analyser: undefined, id: 7 },
{ analyser: "abc", id: 6 },
];
const currentNodee = { analyser: "abc", id: 7 };
allNodes.map(node => {
if (node.analyser == currentNodee.analyser && node.id == currentNodee.id) {
console.log(node.analyser)
}
})
CodePudding user response:
Presented below is one possible way to achieve the desired objective.
Code Snippet
const rd = document.getElementById("rd");
const btn = document.getElementById("myBtn");
const btn2 = document.getElementById("myBtn2");
const allNodes = [{
analyser: undefined,
id: 7
},
{
analyser: "abc",
id: 6
},
];
const currentNodee = {
analyser: "abc",
id: 7
};
const currentNodef = {
analyser: "abc",
id: 6
};
const getResult = (curr) => {
const tgt = allNodes.find(
({ analyser, id }) => curr.id === id
);
if (tgt) {
if (
tgt.analyser &&
tgt.analyser === curr.analyser
) {
return JSON.stringify(tgt);
} else {
return "print nothing";
}
} else {
return "not found"
};
};
btn.textContent = 'Search analyser id=7';
btn.addEventListener('click', () => {
rd.innerText = getResult(currentNodee);
});
btn2.textContent = 'Search analyser id=6';
btn2.addEventListener('click', () => {
rd.innerText = getResult(currentNodef);
});
<div>
Search result: <div id="rd">empty</div>
<button id="myBtn" />
<button id="myBtn2" />
</div>
Printing in single line can be done using JSON.stringify()
as demonstrated in the above code snippet.