Use Lodash to Find Objects in an Array Matches an Id (Complex, Drilldown)

Use Lodash to find objects in an array matches an id (complex, drilldown)

You can combine Array.prototype.filter(), Array.prototype.some() and Array.prototype.includes()

Code:

const ids = ["5ae05bf146e0fbeeb1869d7b", "5ae03c56dc0e82fd2f2746d6"]const data = {"interactions":[{"author":{"id":"10158567383880542","name":"Stephen Wilson"},"meta":{"tags":[{"id":"5ae04788c9e77cb0a03b3228"},{"id":"5ae04788c9e77cb0a03b365"}]}},{"author":{"id":"10158567383880543","name":"Phil Murray"},"meta":{"tags":[{"id":"5ae05bf146e0fbeeb1869d7b"},{"id":"5ae04788c9e77cb0a03b369"}]}},{"author":{"id":"10158567383880543","name":"Steve Jobs"},"meta":{"tags":[{"id":"5ae84b4fc9e77c5db6fbf3f8"},{"id":"5ae04788c9e77cb0a44469"}]}},{"author":{"id":"10158567383880543","name":"John Connor"},"meta":{"tags":[{"id":"5ae84b4fc9e778c5db6fbf3f8"},{"id":"5ae04788c94577cb0a44469"}]}}]};
const result = data.interactions.filter(i => i.meta.tags.some(t => ids.includes(t.id)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter multiple properties of a parent child array which could be several tree level deep

I have a way to do it. It should be fairly performant but we might also want to swap out map and reduce etc. for good old for-loops to optimize speed further (I have seen various blogs and articles comparing speed of forEach, map etc. to for-loop and for-loops seem to win)

Here's a demo (also here: https://codepen.io/Alexander9111/pen/abvojzN):

const myFiles = [  { id: 11, file: "Music", parentId: null },  { id: 12, file: "mp3", parentId: 11 },  { id: 14, file: "pop", parentId: 12 },  { id: 15, file: "theme.mp3", dateModified: "2015-03-01", size: 85,  parentId: 14 },  { id: 16, file: "rock", parentId: 12 },  { id: 17, file: "soft.mp3", dateModified: "2015-05-13", size: 98, parentId: 16 },  { id: 18, file: "else.txt", dateModified: "2015-03-03", size: 90, parentId: null },  { id: 21, file: "Documents", parentId: null },  { id: 2, file: "txt", parentId: 21 },  { id: 3, file: "todo.txt", dateModified: "2015-05-12", size: 0.7, parentId: 2 },  { id: 4, file: "pdf", parentId: 21 },  { id: 22, file: "map2.pdf", dateModified: "2015-05-21", size: 2.9, parentId: 4 },  { id: 5, file: "map.pdf", dateModified: "2015-05-21", size: 3.1, parentId: 4 },  { id: 6, file: "internet-bill.pdf", dateModified: "2015-05-12", size: 1.4, parentId: 4 },  { id: 7, file: "xls", parentId: 21 },  { id: 8, file: "compilation.xls", dateModified: "2014-10-02", size: 2.3, parentId: 7 },  { id: 9, file: "misc", parentId: 21 },  { id: 10,  file: "something.txt", dateModified: "2015-02-26", size: 0.4,  parentId: 9 }];
//example how to use the "<3" string - better way than using eval():const columnFilters = { file: "map", size: "<3.2" }; //, size: "<3" const isSizeValid = Function("return " + myFiles[11].size + "<3")();//console.log(isSizeValid);
const myObj = myFiles.reduce((aggObj, child) => { aggObj[child.id] = child; //the filtered data is used again as each subsequent letter is typed //we need to delete the ._used property, otherwise the logic below //in the while loop (which checks for parents) doesn't work: delete aggObj[child.id]._used; return aggObj;}, {});
function filterMyFiles(myArray, columnFilters){ const filteredChildren = myArray.filter(a => { for (let key in columnFilters){ //console.log(key) if (a.hasOwnProperty(key)){ const strContains = String(a[key]).includes(columnFilters[key]); const re = /(?:(?:^|[-+<>=_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-<>=]?\d+)?\s*))+$/; const comparison = re.test(columnFilters[key]) && Function("return " + a[key] + columnFilters[key])(); if (strContains || comparison){ //don't return true as need to check other keys in columnFilters }else{ //console.log('false', a) return false; } } else{ return false; } } //console.log('true', a) return true; }) return filteredChildren;}
const initFiltered = filterMyFiles(myFiles, columnFilters);
const finalWithParents = initFiltered.map(child => { const childWithParents = [child]; let parent = myObj[child.parentId]; while (parent){ //console.log('parent', parent) parent._used || childWithParents.unshift(parent) myObj[parent.id]._used = true; parent = myObj[parent.parentId] || false; } return childWithParents;}).flat();
console.log(finalWithParents)
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to create array of object from HTML Table in javascript?

Verified that you have the tbody node inside a table node. You can get the items with document.querySelectorAll("#metadata tr"):

const btn = document.querySelector("button");
btn.addEventListener("click", () => {
const elements = document.querySelectorAll("#metadata tr");
const result = Array.from(elements).map(tr => {
const childs = tr.querySelectorAll("input");
return {
p1: childs[0].value,
p2: childs[1].value
};
});

console.log(result);
});
<table>
<tbody id="metadata">
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
</tbody>
</table>
<button>Get Data</button>

How can I display a JavaScript object?

If you want to print the object for debugging purposes, use the code:

var obj = {
prop1: 'prop1Value',
prop2: 'prop2Value',
child: {
childProp1: 'childProp1Value',
},
}
console.log(obj)

will display:

screenshot console chrome

Note: you must only log the object. For example, this won't work:

console.log('My object : ' + obj)

Note ': You can also use a comma in the log method, then the first line of the output will be the string and after that, the object will be rendered:

console.log('My object: ', obj);

Update value of nested objects using lodash

I'm personally a big fan of lodash, but there's really no need for it here:

data = [{    id: 1,    text: 'one',    children: [{        id: 1.1,        text: 'one point one',        children: [            {id: 123, text: 'blah'}        ]    }]}, {    id: 66,    children: [        {id: 123, text: 'blah'}    ]}];

let update = (id, text) => obj => { if (obj.id === id) obj.text = text; else if (obj.children) obj.children.forEach(update(id, text));};
data.forEach(update(123, 'hello'));
console.log(data);

React: Map over Array of Obects (fake data) to render an Array of words

You should map on the spellingWords array:

function WordList({ words }) {
return (
<div>
{
words[0].spellingWords.map( word =>
(<h1 key={word}>{word}</h1>)
)
}
</div>
);
}



Related Topics



Leave a reply



Submit