0

I'm trying to create the following thing, I couldn't find any success, let me know if there's a way :) I have 2 variables called text1 and text2, each one of them should represent a key inside an object and the value of the key will be the data variables.

In the beginning, the object will start as empty, and I need to create a function that will create that object inside the object as many times as need, it can be a case where the text will have more than 3 keys, for e.g. items.courses.lessons.assets.title etc.. so the function must be dynamic. notice that the function must check if the key already exists so it will not overwrite it if there is another text with the same starting keys (see example below)

const data1 = 'hello';
const text1 = 'lessons.first.title';

const data2 = 'hello there';
const text2 = 'lessons.first.description';

// how the end result should look like
const result = {
    lessons: {
        first: {
            title: 'hello',
            description: 'hello there',
        },
    },
};

Thanks! 😁😁

1
  • Simple split and loop with bracket notation Commented Apr 12, 2021 at 18:55

3 Answers 3

1

Split the path up, remove the last part. Loop over an object with the remaining path. When you get to the end, set the property wit the value.

function setProp(obj, path, value) {
  var parts = path.split(".");
  var last = parts.pop();
  var current = parts.reduce(function (acc, part) {
    acc[part] = acc[part] || {};
    return acc[part];
  }, obj);
  current[last] = value;
}

const data1 = 'hello';
const text1 = 'lessons.first.title';

const data2 = 'hello there';
const text2 = 'lessons.first.description';

var myObj = {};
setProp(myObj, text1, data1 );
setProp(myObj, text2, data2);
console.log(myObj);

Sign up to request clarification or add additional context in comments.

1 Comment

You can shorten the reduce into parts.reduce((acc, part) => (acc[part] ||= {}), obj) if you don't mind using newer features.
0

Here's how I did it :)

const data1 = 'hello';
const text1 = 'lessons.first.title';

const data2 = 'hello there';
const text2 = 'lessons.first.description';

const res = {};
const addProp = (keys, value) => {
    let temp = res;
  const len = keys.split('.').length
    keys.split('.').forEach((key,index)=>{
    if(!temp[key]) {
        temp[key] = {};
    }
    if(index === len - 1){
        temp[key] = value;
    }
    temp = temp[key];
  });
}

addProp(text1, data1);
addProp(text2, data2);
console.log(res);

Comments

0

Here is my attempt

function constructObj(obj, path, value) {
  const pathArray = path.split('.');

  let currentNode = obj;
  for (let i = 0; i < pathArray.length; i++) {
    const path = pathArray[i];

    if (i === pathArray.length - 1) { // if on last element assign the value
      currentNode[path] = value;
    }

    if (currentNode[path] === undefined) { // check if key exists
      const newObj = {};
      currentNode[path] = newObj; 
      currentNode = newObj;
    } else {
      currentNode = currentNode[path];
    }
  }
}


const result = {};
const data1 = 'hello';
const text1 = 'lessons.first.title';

constructObj(result, text1, data1);

const data2 = 'hello there';
const text2 = 'lessons.first.description';
constructObj(result, text2, data2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.