Find value in javascript array of objects deeply nested with ES6 - javascript

In an array of objects I need to find a value -- where key is activity : However the activity key can be deeply nested in the array like so:
const activityItems = [
{
name: 'Sunday',
items: [
{
name: 'Gym',
activity: 'weights',
},
],
},
{
name: 'Monday',
items: [
{
name: 'Track',
activity: 'race',
},
{
name: 'Work',
activity: 'meeting',
},
{
name: 'Swim',
items: [
{
name: 'Beach',
activity: 'scuba diving',
},
{
name: 'Pool',
activity: 'back stroke',
},
],
},
],
},
{} ...
{} ...
];
So I wrote a recursive algorithm to find out if a certain activity is in the array:
let match = false;
const findMatchRecursion = (activity, activityItems) => {
for (let i = 0; i < activityItems.length; i += 1) {
if (activityItems[i].activity === activity) {
match = true;
break;
}
if (activityItems[i].items) {
findMatchRecursion(activity, activityItems[i].items);
}
}
return match;
};
Is there an ES6 way of determining if an activity exists in an array like this?
I tried something like this:
const findMatch(activity, activityItems) {
let obj = activityItems.find(o => o.items.activity === activity);
return obj;
}
But this won't work with deeply nested activities.
Thanks

You can use some() method and recursion to find if activity exists on any level and return true/false as result.
const activityItems = [{"name":"Sunday","items":[{"name":"Gym","activity":"weights"}]},{"name":"Monday","items":[{"name":"Track","activity":"race"},{"name":"Work","activity":"meeting"},{"name":"Swim","items":[{"name":"Beach","activity":"scuba diving"},{"name":"Pool","activity":"back stroke"}]}]}]
let findDeep = function(data, activity) {
return data.some(function(e) {
if(e.activity == activity) return true;
else if(e.items) return findDeep(e.items, activity)
})
}
console.log(findDeep(activityItems, 'scuba diving'))

While not as elegant as a recursive algorithm, you could JSON.stringify() the array, which gives this:
[{"name":"Sunday","items":[{"name":"Gym","activity":"weights"}]},{"name":"Monday","items":[{"name":"Track","activity":"race"},{"name":"Work","activity":"meeting"},{"name":"Swim","items":[{"name":"Beach","activity":"scuba diving"},{"name":"Pool","activity":"back stroke"}]}]}]
You could then use a template literal to search for the pattern:
`"activity":"${activity}"`
Complete function:
findMatch = (activity, activityItems) =>
JSON.stringify(activityItems).includes(`"activity":"${activity}"`);
const activityItems = [{
name: 'Sunday',
items: [{
name: 'Gym',
activity: 'weights',
}, ],
},
{
name: 'Monday',
items: [{
name: 'Track',
activity: 'race',
},
{
name: 'Work',
activity: 'meeting',
},
{
name: 'Swim',
items: [{
name: 'Beach',
activity: 'scuba diving',
},
{
name: 'Pool',
activity: 'back stroke',
},
],
},
],
}
];
findMatch = (activity, activityItems) =>
JSON.stringify(activityItems).includes(`"activity":"${activity}"`);
console.log(findMatch('scuba diving', activityItems)); //true
console.log(findMatch('dumpster diving', activityItems)); //false

First, your function could be improved by halting once a match is found via the recursive call. Also, you're both declaring match outside, as well as returning it. Probably better to just return.
const findMatchRecursion = (activity, activityItems) => {
for (let i = 0; i < activityItems.length; i += 1) {
if (activityItems[i].activity === activity) {
return true;
}
if (activityItems[i].items && findMatchRecursion(activity, activityItems[i].items) {
return true;
}
}
return false;
};
There's no built in deep search, but you can use .find with a named function if you wish.
var result = !!activityItems.find(function fn(item) {
return item.activity === "Gym" || (item.items && item.items.find(fn));
});

We now use object-scan for simple data processing tasks like this. It's really good once you wrap your head around how to use it. Here is how one could answer your questions
// const objectScan = require('object-scan');
const find = (activity, input) => objectScan(['**'], {
abort: true,
rtn: 'value',
filterFn: ({ value }) => value.activity === activity
})(input);
const activityItems = [{"name":"Sunday","items":[{"name":"Gym","activity":"weights"}]},{"name":"Monday","items":[{"name":"Track","activity":"race"},{"name":"Work","activity":"meeting"},{"name":"Swim","items":[{"name":"Beach","activity":"scuba diving"},{"name":"Pool","activity":"back stroke"}]}]}]
console.log(find('scuba diving', activityItems));
// => { name: 'Beach', activity: 'scuba diving' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan

Related

How to fix the count variable value in a recursive method using react and javascript?

I have data like below:
const arr_obj = [
{
id: '1',
children: [],
type: 'TYPE1',
},
{
id: '2',
children: [
{
id: '1',
children: [
{
//some attributes
},
],
type: 'MAIN',
},
{
id: '2',
children: [
{
//some attributes
},
],
type: 'MAIN',
},
{
id: '3',
children: [
{
//some attributes
},
],
type: 'MAIN',
},
],
type: 'TYPE2',
},
{
id: '3',
children: [
{
id: '4',
children: [
{
//some attributes
},
],
type: 'MAIN',
},
{
id: '5',
children: [
{
//some attributes
},
],
type: 'MAIN',
},
{
id: '6',
children: [
{
//some attributes
},
],
type: 'MAIN',
},
],
type: 'TYPE2',
},
];
I have to find out the count of type: 'MAIN'. these 'MAIN' will be within type: 'TYPE2'
So the expected count is 6.
below is the code,
const ParentComponent = () => {
const findCount = (arr_obj) => {
let count = 0;
const expectedCount = 2;
const loop = (children) => {
for (const obj of children) {
const { type, children } = obj;
if (type === 'TYPE2') {
loop(children);
} else if (type === 'MAIN') {
++count;
if (count > expectedCount) return;
}
}
};
loop(children);
return count > expectedCount;
};
const output = findCount(arr_obj);
return (
//some jsx rendering
);
};
The above code works fine, but I want to make a loop (children) function a pure function. I am not sure how to do it.
The problem now is: I define variables outside the loop method.
How can I define everything as arguments to the function? You could move the function outside the component.
I have tried something like below to make it a pure function
const loop = (children, count = 0) => {
if (!children) return;
for (const obj of children) {
const { type, children } = obj;
if (type === 'TYPE2') {
loop(children, count + 1);
} else if (type === 'MAIN') {
++count;
if (count > expectedCount) return;
}
}
console.log('count', count); //this is 0 always when i log
return count;
};
const ParentComponent = () => {
const output = React.useMemo(() => {
return loop(arr_obj);
}, [arr_obj]);
console.log('output', output); // output is always false
return (
//some jsx rendering
)
};
Now the problem with above code is that the count is always 0. I am not sure where the problem is.
Your approach is fine: you update count by passing it as a parameter and by returning its updated value. However, the function returns at three spots and you only return count at the third spot. Furthermore, you call loop recursively, but there, you don't use its return value and you should pass count instead of count + 1 as an argument.
You need to make the following changes:
Inside loop, replace return; with return count; two times.
Inside loop, replace loop(children, count + 1); with count = loop(children, count);
Now, if you would remove if (count > expectedCount) return;, you would get 6 as the result.
I'm not sure what exactly you want but I don't think you'd need to make it complicated with recursion. You can simply achieve the same function like this:
const findCount = (arr) => {
const filteredArray = arr
.filter(el => el.type === 'TYPE2')
// removed all elements whose type is not TYPE2
.map(el => el.children)
// replaced all element with element's children array
.flat()
// flattened the array
.filter(el => el.type === 'MAIN');
// removed all elements whose type is not MAIN
return filteredArray.length;
};

How to exclude certain property from the list in NodeJS

I'm having the below list and I would like to add only these property names PRODUCT_TYPE, PRODUCT_TERM, PRODUCT_ID in myProduct. I want to ignore rest of the properties - I've around 100 properties and want to filter only a few of them from myProduct
Please find my code below:
const obj = {
myProduct: [
{
name: "PRODUCT_PRICE",
value: "234.324",
},
{
name: "PRODUCT_NAME",
value: "Insurance",
},
{
name: "PRODUCT_TYPE",
value: "Life",
},
{
name: "PRODUCT_TERM",
value: "Long",
},
{
name: "PRODUCT_ID",
value: "AP3232343JKD",
},
{
name: "PRODUCT_ENABLED",
value: "TRUE",
},
],
};
const allowedNames = [
'PRODUCT_TYPE',
'PRODUCT_TERM',
'PRODUCT_ID'
];
const updateCertainProperties = {
PRODUCT_ID: "app.productID",
PRODUCT_ENABLED: "app.product.enabled"
};
const productName = "testProduct_3234dfasfdk3msldf23";
const environment = obj.myProduct.map((o) => {
obj.myProduct.filter(product => allowedNames.includes(product.name));
if (updateCertainProperties[o.name]) o.name = updateCertainProperties[o.name];
if (o.name === "PRODUCT_NAME") o.value = productName;
return obj.myProduct;
});
console.log(obj.myProduct)
Expected output:
[
{ name: 'PRODUCT_NAME', value: 'testProduct_3234dfasfdk3msldf23' },
{ name: 'PRODUCT_TYPE', value: 'Life' },
{ name: 'PRODUCT_TERM', value: 'Long' },
{ name: 'app.productID', value: 'AP3232343JKD' },
{ name: 'app.product.enabled', value: 'TRUE' }
]
Can someone please help me how can I achieve this? Appreciated your help in advance!
You can create an array of allowed names and filter them out using includes()
css just for prettier output
UPDATE
added updateCertainProperties object values into allowedNames array and moved filter outside environment map.
const obj = {
myProduct: [
{
name: "PRODUCT_PRICE",
value: "234.324",
},
{
name: "PRODUCT_NAME",
value: "Insurance",
},
{
name: "PRODUCT_TYPE",
value: "Life",
},
{
name: "PRODUCT_TERM",
value: "Long",
},
{
name: "PRODUCT_ID",
value: "AP3232343JKD",
},
{
name: "PRODUCT_ENABLED",
value: "TRUE",
},
],
};
const allowedNames = [
'PRODUCT_TYPE',
'PRODUCT_TERM',
'PRODUCT_NAME'
];
const updateCertainProperties = {
PRODUCT_ID: "app.productID",
PRODUCT_ENABLED: "app.product.enabled"
};
allowedNames.push(...Object.values(updateCertainProperties));
const productName = "testProduct_3234dfasfdk3msldf23";
const environment = obj.myProduct.map((o) => {
if (updateCertainProperties[o.name]) o.name = updateCertainProperties[o.name];
if (o.name === "PRODUCT_NAME") o.value = productName;
return obj.myProduct;
});
obj.myProduct = obj.myProduct.filter(product => allowedNames.includes(product.name));
console.log(obj.myProduct)
.as-console-wrapper {
max-height: unset !important;
top: 0;
}
It sounds like you're describing filtering an array, not "excluding properties". You have an array of objects, with each object consisting of a name property and value property. And you only want objects with specific values in their name property.
Using .filter on the array, it might look something like this:
obj.myProduct = obj.myProduct.filter(p => (
p.name === 'PRODUCT_TYPE' ||
p.name === 'PRODUCT_TERM' ||
p.name === 'PRODUCT_ID'));
This would filter out all elements of the array which don't match the supplied condition.

Find by key get value and replace by second json value in nested json object

I have an json object(firstObj) It can be nested and I have an second object containing key/value pair. I want to replace the second object's value by first one by matching value and do it's operation.
let firstObj = {
amount_money: {
amount: {
mapped_field: 'payment_amt',
operation: '/10'
},
currency: {
mapped_field: 'payment_cur',
operation: null
}
},
source_id: {
mapped_field: 'request_id',
operation: null
},
ship: [
{ mapped_field: 'ship_country[0]', operation: null },
{ mapped_field: 'ship_country[1]', operation: null }
]
};
my second object
let secondObj = {
payment_amt: 100,
payment_cur: 'USD',
request_id: '123ASD',
ship_country: [
{ code: 'USA', Title: 'America' },
{ code: 'UK', Title: 'England' }
]
};
I want something like this
{
amount_money: {
amount: 10
currency: 'USD'
},
source_id: '123ASD',
ship: [ {America: 'USA'}, {England: 'UK'}]
}
Really appreciate your kind help,
Thank you!
Update
If you don't know how many nested nodes are there. There is a more overall solution using recursion.
Here is the solution:
const firstObj = {
source_name: {
mapped_field: 'request_name',
operation: null,
},
amount_money: {
amount: {
mapped_field: 'payment_amt',
operation: '/10',
},
currency: {
mapped_field: 'payment_cur',
operation: null,
},
},
source_id: {
mapped_field: 'request_id',
operation: null,
},
nested: {
nested: {
nested: {
nested: {
mapped_field: 'mapping_nested',
operation: null,
},
},
},
},
};
let secondObj = {
payment_amt: 100,
payment_cur: 'USD',
request_id: '123ASD',
request_name: 'Dollar',
mapping_nested: 'Hello',
};
const procedure = (firstObj, parentObj = {}, nestedObj = {}) => {
for (const [key, value] of Object.entries(firstObj)) {
if (value.hasOwnProperty('mapped_field') && value.hasOwnProperty('operation')) {
nestedObj[key] = value.operation
? eval(secondObj[value.mapped_field] + value.operation)
: secondObj[value.mapped_field];
} else {
nestedObj[key] = {};
procedure(value, parentObj, nestedObj[key]);
}
}
return (parentObj = { ...nestedObj });
};
const result = procedure(firstObj);
console.log(JSON.stringify(result));
// {"source_name":"Dollar","amount_money":{"amount":10,"currency":"USD"},"source_id":"123ASD","nested":{"nested":{"nested":{"nested":"Hello"}}}}
Old answer
I don't know how many nested in your firstObj. But this code below can solve the example which you give.
I replace the second object's value by first one by matching value.
If operation not equal null, use eval() function evaluates JavaScript code represented as a string.
const result = {};
for (const [parentKey, parentValue] of Object.entries(firstObj)) {
result[parentKey] = {};
for (const [childKey, childValue] of Object.entries(parentValue)) {
result[parentKey][childKey] = childValue.operation
? eval(secondObj[childValue.mapped_field] + childValue.operation)
: secondObj[childValue.mapped_field];
}
}
console.log(result); //{ amount_money: { amount: 10, currency: 'USD' } }
Note: If firstObj have only one key like amount_money, you can make your code precise by using only one loop.
To address the updated question
.as-console-wrapper {max-height: 100% !important; top: 0}
<script type="module">
import objectScan from 'https://cdn.jsdelivr.net/npm/object-scan#18.1.2/lib/index.min.js';
const myTemplate = { amount_money: { amount: { mapped_field: 'payment_amt', operation: '/10' }, currency: { mapped_field: 'payment_cur', operation: null } }, source_id: { mapped_field: 'request_id', operation: null }, ship: [{ mapped_field: 'ship_country[0]', operation: null }, { mapped_field: 'ship_country[1]', operation: null }] };
const myVariables = { payment_amt: 100, payment_cur: 'USD', request_id: '123ASD', ship_country: [{ code: 'USA', Title: 'America' }, { code: 'UK', Title: 'England' }] };
const apply = (input, operation) => {
if (operation === null) {
return input;
}
const action = /(?<op>[/+])(?<v>\d+)/g.exec(operation);
if (action === null) {
throw new Error(`Unknown operation: ${operation}`);
}
if (action.groups.op === '/') {
return input / action.groups.v;
}
// action.groups.op === '+'
return input + action.groups.v;
};
const compile = objectScan(['**.mapped_field'], {
rtn: 'count',
filterFn: ({ gparent, gproperty, parent, value, context }) => {
const data = objectScan([value], { rtn: 'value', abort: true })(context);
if (data === undefined) {
return false;
}
gparent[gproperty] = apply(data, parent.operation);
return true;
}
});
console.log(compile(myTemplate, myVariables));
// => 5
console.log(myTemplate);
// => { amount_money: { amount: 10, currency: 'USD' }, source_id: '123ASD', ship: [ { code: 'USA', Title: 'America' }, { code: 'UK', Title: 'England' } ] }
</script>
Disclaimer: I'm the author of object-scan
Old Answer (pre edit of question)
Here is a generic solution using object-scan.
.as-console-wrapper {max-height: 100% !important; top: 0}
<script type="module">
import objectScan from 'https://cdn.jsdelivr.net/npm/object-scan#18.1.2/lib/index.min.js';
const template = { amount_money: { amount: { mapped_field: 'payment_amt', operation: '/10' }, currency: { mapped_field: 'payment_cur', operation: null } }, source_id: { mapped_field: 'request_id', operation: null } }
const values = { payment_amt: 100, payment_cur: 'USD', request_id: '123ASD' };
const apply = (input, operation) => {
if (operation === null) {
return input;
}
const action = /(?<op>[/+])(?<v>\d+)/g.exec(operation);
if (action === null) {
throw new Error(`Unknown operation: ${operation}`);
}
if (action.groups.op === '/') {
return input / action.groups.v;
}
// action.groups.op === '+'
return input + action.groups.v;
};
const compile = objectScan(['**.*.mapped_field'], {
rtn: 'count',
filterFn: ({ gparent, gproperty, parent, value, context }) => {
if (value in context) {
gparent[gproperty] = apply(context[value], parent.operation);
return true;
}
return false;
}
});
console.log(compile(template, values));
// => 3
console.log(template);
// => { amount_money: { amount: 10, currency: 'USD' }, source_id: '123ASD' }
</script>
Disclaimer: I'm the author of object-scan
Important:
Note that this does modify the template object. You could clone it, if that is not desired.
You could use eval, but it's considered dangerous. It's a bit more work, but you should probably implement all supported operations yourself as I've started in the "apply" function.
You might be able to use eg safe-eval, but I have no experience with it and don't know how safe it is. If you are worried about any sort of injection attack, don't use it.
Edit (as requested in comment)
How this works:
apply is a helper function, taking the input and an operation. We use a regex to determine the operator and then apply it against the input
compile is the core logic. We target the field with **.*.mapped_field, where the single * ensures that we are targeting an object and not an array
in filterFn we check if the value is known in context (which is values). If that is the case update the the value using the grandparent (gparent) and grandproperty (gproperty). All the parameters of filterFn are relative to the target (in this case mapped_field)
count is just the return value (in this case how often true was returned from filterFn
This is all documented n great detail in object-scan. Have a look there. It might also greatly help your understanding to put in come log statements!

Create a tree from a list of strings containing paths

See edit below
I wanted to try and create a tree from a list of paths and found this code on stackoverflow from another question and it seems to work fine but i would like to remove the empty children arrays instead of having them showing with zero items.
I tried counting r[name].result length and only pushing it if it greater than zero but i just end up with no children on any of the nodes.
let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];
let result = [];
let level = {result};
paths.forEach(path => {
path.split('/').reduce((r, name, i, a) => {
if(!r[name]) {
r[name] = {result: []};
r.result.push({name, children: r[name].result})
}
return r[name];
}, level)
})
console.log(result)
EDIT
I didnt want to ask directly for the purpose i am using it for but if it helps i am trying to create an array like this: (this is a copy paste of the config needed from ng-zorro cascader)
const options = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
isLeaf: true
}
]
},
{
value: 'ningbo',
label: 'Ningbo',
isLeaf: true
}
]
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
isLeaf: true
}
]
}
]
}
];
from an array of flat fields like this:
let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];
I suggest to use a different approach.
This approach takes an object and not an array for reaching deeper levels and assigns an array only if the nested level is required.
let paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"],
result = paths
.reduce((parent, path) => {
path.split('/').reduce((r, name, i, { length }) => {
let temp = (r.children ??= []).find(q => q.name === name);
if (!temp) r.children.push(temp = { name, ...(i + 1 === length && { isLeaf: true }) });
return temp;
}, parent);
return parent;
}, { children: [] })
.children;
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

How could I find a json object by id using nodejs/js

So I want to get the object by the id 1 in this object:
let users = {
'users': {
'user1': {
'id': '1',
'name': 'Brandon',
'DOB': '05/04/2000'
},
'user2': {
'id': '2',
'name': 'Jefferson',
'DOB': '05/19/2004'
}
}
}
and I want it to return the entire 'user1' array and log it, does anyone know how I could do this?
I looked all over stackoverflow, and docs, and couldn't find a way to do this. Could I get some help?
There are a few approaches, both of these should roughly achieve what you're looking for:
let users = {
'users': {
'user1': {
'id': '1',
'name': 'Brandon',
'DOB': '05/04/2000'
},
'user2': {
'id': '2',
'name': 'Jefferson',
'DOB': '05/19/2004'
}
}
}
const findUserById = (id) => {
const key = Object.keys(users.users).find(user => users.users[user].id === '1')
return users.users[key]
}
console.log(findUserById('1'))
let users = {
'users': {
'user1': {
'id': '1',
'name': 'Brandon',
'DOB': '05/04/2000'
},
'user2': {
'id': '2',
'name': 'Jefferson',
'DOB': '05/19/2004'
}
}
}
const findUserById = (id) => {
const [key, user] = Object.entries(users.users).find(([key, user]) => user.id === '1');
return user;
}
console.log(findUserById('1'))
While the answer by skovy is right and this is what you should be doing in an actual production setting, I would advise against applying it immediately in your situation.
Why? Your question shows that you first need to learn some basic principles any JavaScript programmer should have, that is:
How to iterate over contents of an object
The simplest method used to iterate over an object's keys is the for .. in loop. When iterating over an object's keys using the for .. in loop, the code inside the curly brackets will be executed once for every key of the object we are iterating.
let users = {
"user1": {
"id": 1
},
"user2": {
"id": 2
}
}
for (let key in users) {
console.log(key);
}
The above code will print:
user1
user2
Proceeding from that, it should be clear how to find the element we want:
let foundUser = null;
for (let key in users) {
if (users[key].id === 1) {
foundUser = users[key];
break;
}
}
// now found user is our user with id === 1 or null, if there was no such user
When not to do that
If you have a complex object which is a descendant of another object and don't want to iterate over inherited properties, you could instead get an array of current object's keys with Object.keys:
let users = {
"user1": {
"id": 1
},
"user2": {
"id": 2
}
}
const keys = Object.keys(users) // now this is an array containing just keys ['user1', 'user2'];
let foundUser = null;
// now you can iterate over the `keys` array using any method you like, e.g. normal for:
for (let i = 0; i < keys.length; i++) {
if (users[keys[i]].id === 1) {
foundUser = users[keys[i]];
break;
}
}
// or alternatively `for of`:
for (for key of keys) {
if (users[key].id === 1) {
foundUser = users[key];
break;
}
}
Other options
You could use Object.values to get an array containing all values of the object:
let users = {
"user1": {
"id": 1
},
"user2": {
"id": 2
}
}
const values = Object.values(users); // values: [{"id":1},{"id":2}]
You can now find the entry you want on your own:
let foundUser = null
for (let i = 0; i < values.length; i++) {
if (values[i].id === 1) {
foundUser = values[i];
break;
}
}
Or using the Array's find method:
let foundUser = values.find(user => user.id === 1);
// now foundUser contains the user with id === 1
Or, shorter and complete version:
let users = {
"user1": {
"id": 1
},
"user2": {
"id": 2
}
}
const foundUser = Object.values(users).find(user => user.id === 1);
// now foundUser is `{ id: 1 }`
Not a big fan of reinventing the wheel. We use object-scan for most of our data processing now. It's very handy when you can just use a tool for that kind of stuff. Just takes a moment to wrap your head around how to use it. Here is how it could answer your questions:
// const objectScan = require('object-scan');
const find = (id, data) => objectScan(['**.id'], {
abort: true,
rtn: 'parent',
filterFn: ({ value }) => value === id
})(data);
const users = { users: { user1: { id: '1', name: 'Brandon', DOB: '05/04/2000' }, user2: { id: '2', name: 'Jefferson', DOB: '05/19/2004' } } };
console.log(find('1', users));
// => { id: '1', name: 'Brandon', DOB: '05/04/2000' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
A simple for loop would do it:
let users = {
'users': {
'user1': {
'id': '1',
'name': 'Brandon',
'DOB': '05/04/2000'
},
'user2': {
'id': '2',
'name': 'Jefferson',
'DOB': '05/19/2004'
}
}
}
let desiredUser = {};
Object.keys(users.users).forEach((oneUser) => {
if(users.users[oneUser].id === "1")
desiredUser = users.users[oneUser];
});
console.log(desiredUser);
You can also use reduce for this... as well as if you wanted to return the "entire" object, you could do:
let USER_LIST = {
'users': {
'user1': {
'id': '1',
'name': 'Brandon',
'DOB': '05/04/2000'
},
'user2': {
'id': '2',
'name': 'Jefferson',
'DOB': '05/19/2004'
}
}
}
function findUserById(id){
return Object.entries(USER_LIST.users).reduce((a, [user, userData]) => {
userData.id == id ? a[user] = userData : '';
return a;
}, {});
}
console.log(findUserById(1));
I agree with the Answers. just a short and simple way is to use .find() method
//--data returned-----//
data = [{"Id":22,"Title":"Developer"},{"Id":45,"Title":"Admin"}]
fs.readFile('db.json','utf8', function(err,data){
var obj = JSON.parse(data);
console.log(obj);
var foundItem = obj.find(o=>o.Id==id);
console.log(foundItem);
});

Categories

Resources