Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join(';') on nested object

I'm trying to join all values from an object to semi colon separation, it works fine if the object is just one level:

obj = { 
    name: "one"
    additionalInfo: "hello"
    ...
};

Object.values(obj).join(';')

Result: one;hello

But if the object is nested:

obj = { 
    name: "one"
    additionalInfo: {
         description: "hello",
         ...
    }
};

Object.values(obj).join(';')

Result: one;[object Object]

The rest of the values except name is of course [object Object]. How can I join the level 2 values also?

The result I want is:

one;hello
like image 725
Robin Avatar asked Jul 30 '26 15:07

Robin


2 Answers

You can take a recursive approach by making sure to convert any nested objects before joining the values of the entire level of the object:

function joinObjectValues(obj, delimiter = ";") {
  return Object.values(obj)
    .map(val => {
      //convert any objects recursively
      if (typeof val === "object") {
        return joinObjectValues(val, delimiter);
      }

      return val;
    })
    .join(delimiter)
}

let objOneLevel = {
  name: "one"
};

let objTwoLevels = {
  name: "one",
  additionalInfo: {
    description: "hello",
  }
};

let objThreeLevels = {
  name: "one",
  additionalInfo: {
    description: "hello",
    other: {
      customField: "world"
    }
  }
};


console.log(joinObjectValues(objOneLevel))
console.log(joinObjectValues(objTwoLevels))
console.log(joinObjectValues(objThreeLevels))
like image 196
VLAZ Avatar answered Aug 02 '26 04:08

VLAZ


You can use recursive function and loop through all the property like the following way:

var obj = { 
    name: "one",
    additionalInfo: {
         description: "hello",
    }
};
var val = [];
function getValue(obj){
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (typeof obj[property] == "object") {
        getValue(obj[property]);
      } else {
        val.push(obj[property]);          
      }
    }
  }
  return val.join(';');
}
var r = getValue(obj);

console.log(r)
like image 29
Mamun Avatar answered Aug 02 '26 04:08

Mamun



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!