fivedoor fivedoor - 4 months ago 12
Javascript Question

looping through objects within an object with Object.assign

The script below currently outputs:

{
"title1": {
"0": "undefined"
},
"title2": "& three",
"title3": "& four"
}


The desired output being:

{
"title1": {
"nested1": "one",
"nested2": "& two"
},
"title2": "& three ",
"title3": "& four"
}


My question is what is required in the if statement to successfully loop through the properties of the [key][innerKey] and pass them through the encode function and return them to 'out'?

I have been trying to solve it using a for loop within the first part of the if statement without success. I figure it needs to follow a logic along the lines of:


  • if arr[key] is an object then

  • output the [key]:

  • then loop through all properties of the [key]

  • and pass them through the function encode

  • and return them to 'out'



thanks.

var arr = {
"title1": {
"nested1": "one",
"nested2": "& two"
},
"title2": "& three ",
"title3": "& four"
};

var encodedValues = Object.keys(arr).reduce(function(out,key,innerKey) {

if (typeof arr[key] == "object") {
return Object.assign(out, {[key]: {[innerKey]: encode(arr[key][innerKey])}})

} else {
return Object.assign(out, {[key]: encode(arr[key])})
}

}, {});

console.log(encodedValues)

Answer

How about something like this? (recursion)

var arr = {
  "title1": {
    "nested1": "one",
    "nested2": "& two"
  },
  "title2": "& three ",
  "title3": "& four"
};

var encode = function(val){ return encodeURI(val) };

var encodeValues = function(arr){
  var obj = {};
    for(var key in arr){
    if(typeof arr[key] == "object"){
      obj[key] = encodeValues(arr[key]);
    }else{
      obj[key] = encode(arr[key]);
    }
  }
  return obj;
};

var encodedValues = encodeValues(arr);

console.log(encodedValues);