Just getting started looking over lodash and stuck trying to figure out how to remove duplicates from arrays within nested objects.
Working with loop:
const _ = require('lodash');
let data = {
"deviceA": {
"serviceA": [
"Foo",
"Bar",
"Foo Bar A",
"Foo Bar A",
"Foo Bar A"
],
"serviceB": [
"Foo",
"Bar",
"Foo Bar B",
"Foo Bar B",
"Foo Bar B"
]
}
}
for (const key in data) {
for (const key2 in data[key]) {
data[key][key2] = _.uniqWith(data[key][key2], _.isEqual)
}
}
console.log(data)
Is it possible using purely lodash to parse a nested object and update an array to remove duplicates without using a for loop?
I think you can consider a solution without lodash, below is an example of how this can be implemented natively using pure js.
let data = { "deviceA": { "serviceA": [ "Foo", "Bar", "Foo Bar A", "Foo Bar A", "Foo Bar A" ], "serviceB": [ "Foo", "Bar", "Foo Bar B", "Foo Bar B", "Foo Bar B" ] } } const noDup = Object.entries(data).reduce((p, n) => { const a = Object.entries(n[1]).reduce((p1, n1) => ({...p1, [n1[0]]: [...new Set(n1[1])]}), {}) return {...p, [n[0]]: a} }, {}) console.log(noDup)
You can combine uniq and mapValues to achieve it.
let data = { "deviceA": { "serviceA": [ "Foo", "Bar", "Foo Bar A", "Foo Bar A", "Foo Bar A" ], "serviceB": [ "Foo", "Bar", "Foo Bar B", "Foo Bar B", "Foo Bar B" ] }, "deviceB": { "serviceA": [ "A", "A", "Foo Bar A", ], "serviceB": [ "B", "B", "Foo Bar B", ] } } const items = _.mapValues(data, (device) => _.mapValues(device, (service) =>_.uniq(service))) console.log(items)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.