Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Set value in object by path and flatten again with objects and arrays

Im totally clueless how to build this. I am not even sure it is even possible and I've been scratching my head for way too long now.

Lets say I have an object:

const myObj = {
    simple: "test",
    nested: {
        obj: "alright"
    }
}

Now I have found a function that lets me set a value anywhere by specifying a path in that tree. If a key is not already existing in that object, it will be created:

const set = (obj: any, path: any, val: any) => {
    const keys = path.split(".");
    const lastKey = keys.pop();
    const lastObj = keys.reduce((obj: any, key: any) => obj[key] = obj[key] || {}, obj);
    lastObj[lastKey] = val;
};

Example:

set(myObj, "nested.another.iCanEvenGoDeeper", "very deep value");

Result:

const myObj = {
    simple: "test",
    nested: {
        obj: "alright",
        another: {
            iCanEvenGoDeeper: "very deep value"
        }
    }
}

So far so good, but now its required that I can also define a path like this to dynamically build arrays. So that I can call these:

set(myObj, "nested.myArray[0].propInsideArrayElement", "first element")
set(myObj, "nested.myArray[1].propInsideArrayElement", "second element")

that will result in an object that looks like this:

{
    simple: "test",
    nested: {
        obj: "alright",
        myArray: [
            { propInsideArrayElement: "first element" },
            { propInsideArrayElement: "second element" }
        ]
    }
}

It needs to be recursive and work with all scenarios, but I am like I said clueless on if it is even possible. Is there by any chance some utility scripts out there that does this already? If not, can anyone point me in the right direction?

In a next step, I would like to flatten the object to have a one dimensional object again, for the last example it would then look like this:

flatten(myObj);

would then turn to

{
    "simple": "test",
    "nested.obj": "alright",
    "nested.myArray[0].propInsideArrayElement": "first element",
    "nested.myArray[1].propInsideArrayElement": "second element"
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Looks interesting :)

Here is an example for array support based on your own code.

flatten the object is also included (Using recursive calls)

const myObj = {
    simple: "test",
    nested: {
        obj: "alright"
    }
}
const getTypeVal = (currentIndex, length, val) => {
  
}
const set = (obj, path, val) => {
    path = path.replace('[', '.[')
    const keys = path.split(".");
    const lastKey = keys.pop();
    let lastObj = keys.reduce((obj, key, currentIndex) => {
      if(key.includes('[')) {
          return obj[key.substring(1, key.length-1)]
       }
       if(obj[key] && obj[key].length && (keys[currentIndex+1] && keys[currentIndex+1].includes('['))) {
          let nextKey = keys[currentIndex+1] 
          nextKey = nextKey.substring(1, nextKey.length-1)
          !obj[key][nextKey] && obj[key].push({})
       }
       return obj[key] = obj[key] || ((keys[currentIndex+1] && keys[currentIndex+1].includes('[')) ? [{}] : keys[currentIndex+1] ? {} : val)
    }
    , obj);
        lastObj[lastKey] = val;
};
const flatternObj = (obj, result = {}, key ='') =>{
  if(Array.isArray(obj)) {
     obj.forEach((d,i) => {
       result = flatternObj(d, result, key + `[${i}]`)
     })
  }
  else if(typeof obj === 'object') {
    for (const i of Object.keys(obj)) {
       result = flatternObj(obj[i], result, key ? key + `.${i}` : `${i}`)
    }
  }
  else {
     result[key] = obj
  }
  return result;
}


set(myObj, "nested.myArray[0].propInsideArrayElement", "first element")
set(myObj, "nested.myArray[0].propInsideArrayElement2", "first element - 2 ")
set(myObj, "nested.myArrayTwo[0]", 'test')
set(myObj, "nested.myArray[1].propInsideArrayElement", "second element")
set(myObj, "nested.myArray[2]", 'test')
console.log(myObj)

console.log(flatternObj(myObj))

about 4 years ago · Juan Pablo Isaza Report

0

I have totally reworked the deepSet function now. It now supports multiple arrays and gaps in the arrays etc. I think this covers now every usecase. In the end it was way easier to figure the logic out when I started over without the reduce function

export const deepSet = (obj: any, path: string, val: any) => {
    path = path.replaceAll("[", ".[");
    const keys = path.split(".");

    for (let i = 0; i < keys.length; i++) {
        let currentKey = keys[i] as any;
        let nextKey = keys[i + 1] as any;
        if (currentKey.includes("[")) {
            currentKey = parseInt(currentKey.substring(1, currentKey.length - 1));
        }
        if (nextKey && nextKey.includes("[")) {
            nextKey = parseInt(nextKey.substring(1, nextKey.length - 1));
        }

        if (typeof nextKey !== "undefined") {
            obj[currentKey] = obj[currentKey] ? obj[currentKey] : (isNaN(nextKey) ? {} : []);
        } else {
            obj[currentKey] = val;
        }

        obj = obj[currentKey];
    }
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!