Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add new Key/value in nested child object in javascript?

I need to add new key/value pair into nested object array.

this is exisiting array

[{
    "featureId": "67d6e1bf-3919-4dcc-b636-236ab41d431b",
    "featureName": "Test name 1",
    "rules": [
        {
            "ruleId": "a9ab3ce2-e69c-4c0c-b561-1107baed1e68",
            "ruleName": "Sub test 1",
           
        },
        {
            "ruleId": "a9ab3ce2-e69c-4c0c-b561-1107baed1e68",
            "ruleName": "Sub Test 2",
            
        },
        {
            "ruleId": "a8003493-4471-4c8a-85c1-b15706359bb3",
            "ruleName": "Sub Test Three",
           
        }
    ]
},

{...}
]

I need to add additional property into the rules object items.

Expected output is

[{
    "featureId": "67d6e1bf-3919-4dcc-b636-236ab41d431b",
    "featureName": "Test name 1",
    "rules": [
        {
            "ruleId": "a9ab3ce2-e69c-4c0c-b561-1107baed1e68",
            "ruleName": "Sub test 1",
            "temp_id" : 1
           
        },
        {
            "ruleId": "a9ab3ce2-e69c-4c0c-b561-1107baed1e68",
            "ruleName": "Sub Test 2",
            "temp_id" : 1
        },
        {
            "ruleId": "a8003493-4471-4c8a-85c1-b15706359bb3",
            "ruleName": "Sub Test Three",
           "temp_id" : 1 
        }
    ]
},

{...}
]

I need to add temp_id property dynamically. I tried below its not working as expected

Object.keys(_this.existingConfigurations).map((key)=>_this.existingConfigurations[key].rules).reduce((n,id)=>n).map((ny,ni)=>{return {...ny, temp_id : uuid.v4()}});

Here "_this.existingConfigurations" is variable which have the data, i need to do above modification and send to next level.

like image 274
Sathishkumar Avatar asked Dec 05 '25 01:12

Sathishkumar


1 Answers

You could solve this with a couple of maps and a healthy dose of object restructuring:

const initial = [
  {
    featureId: "67d6e1bf-3919-4dcc-b636-236ab41d431b",
    featureName: "Test name 1",
    rules: [
      {
        ruleId: "a9ab3ce2-e69c-4c0c-b561-1107baed1e68",
        ruleName: "Sub test 1",
        temp_id: 1,
      },
      {
        ruleId: "a9ab3ce2-e69c-4c0c-b561-1107baed1e68",
        ruleName: "Sub Test 2",
        temp_id: 1,
      },
      {
        ruleId: "a8003493-4471-4c8a-85c1-b15706359bb3",
        ruleName: "Sub Test Three",
        temp_id: 1,
      },
    ],
  },
];

const result = initial.map((feature) => ({
  ...feature,
  rules: feature.rules.map((rule) => ({ ...rule, temp_id: 1 })),
}));
like image 61
Fredrik A. Avatar answered Dec 06 '25 16:12

Fredrik A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!