I have the following object in React JavaScript,
const obj = {
"time": 1639700933808,
"lastChanges": [
[
{
"op": "add",
"path": "nodes.mpcWlu3JhV.data.nodes.1",
"value": "4aI6ltJzAw"
},
{
"op": "add",
"path": "nodes.4aI6ltJzAw",
"value": {
"id": "4aI6ltJzAw",
"data": {
"name": "DdLookup",
"displayName": "Lookup",
"props": {
"name": "",
"code": ""
},
"custom": {},
"parent": "mpcWlu3JhV",
"isCanvas": false,
"hidden": false,
"nodes": [],
"linkedNodes": {}
}
}
}
],
[
{
"op": "add"
},
{
"op": "replace"
},
{
"op": "add"
}
],
[
{
"op": "replace"
},
{
"op": "add"
}
]
],
"nodes": {
"ROOT": {
"type": {
"resolvedName": "Flex"
},
"isCanvas": false,
"props": {
"className": "oDWyIL2AvKKc6Taj-CEQt"
},
"displayName": "Flex",
"custom": {},
"hidden": false,
"nodes": [
"LFpcm_Fewn"
],
"linkedNodes": {}
},
"LFpcm_Fewn": {
"type": {
"resolvedName": "FormRoot"
},
"isCanvas": true,
"props": {
"name": "123",
"code": "DEV_123"
},
"displayName": "Form",
"custom": {},
"parent": "ROOT",
"hidden": false,
"nodes": [],
"linkedNodes": {
"form-body": "mpcWlu3JhV"
}
},
"mpcWlu3JhV": {
"type": "div",
"isCanvas": true,
"props": {
"className": "_3Op7nHDBF8ya__B1tPDfL_ e1nzbV5Ci4vpgTdE1tSJO FormBodyContainer",
"inGridContainer": false,
"formOrderId": 0
},
"displayName": "div",
"custom": {
"target": "FormBody"
},
"parent": "LFpcm_Fewn",
"hidden": false,
"nodes": [
"ybX-r34-ij",
"4aI6ltJzAw"
],
"linkedNodes": {}
},
"ybX-r34-ij": {
"type": {
"resolvedName": "DdTextBox"
},
"isCanvas": false,
"props": {
"name": "trt",
"code": "DEV_TRT"
},
"displayName": "Text box",
"custom": {},
"parent": "mpcWlu3JhV",
"hidden": false,
"nodes": [],
"linkedNodes": {}
},
"4aI6ltJzAw": {
"type": {
"resolvedName": "DdLookup"
},
"isCanvas": false,
"props": {
"name": "",
"code": ""
},
"displayName": "Lookup",
"custom": {},
"parent": "mpcWlu3JhV",
"hidden": false,
"nodes": [],
"linkedNodes": {}
}
}
};
I am trying to iterate through the nodes
object, I want to find the code
property under the props when the displayName
is Form
. How should I do this?
CodePudding user response:
You can map through the object values:
const nodeValues = Object.values(obj.nodes); // get the nodes values
const allCodes = nodeValues.map(o => {
if(o.displayName == "Form") // check if displayName is Form
return {
code: o.props.code,
linkedNodes: o.props.linkedNodes
} // Get the code or return an object if you need other values
}).filter(v => v)
CodePudding user response:
Similar approach to the answer of @subodhkalika only this one has one iteration rather than use map then filter.
const codes = [];
Object.values(obj.nodes).forEach(node => {
if(node.displayName === "Form" && node.props?.code) {
push(node.props.code);
}
});