Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda