Dominic Bou-Samra
Dominic Bou-Samra

Reputation: 15416

Function to recursively rewrite JSON tree, turning any arrays of 1 item, into an object

Slightly odd request, but I need some help writing a function that will transform some JSON that looks like this (very contrived example sorry):

{
  "userDetails": [
    {
      "name": "DOM",
      "age": 30,
      "comments": [
        {
          "text": "Text"
        },
        {
          "text": "HELLO",
          "stuff": [
            {
              "name": "DOM"
            }
          ]
        }
      ]
    }
  ],
  "items": [
    {
      "name": "A"
    },
    {
      "name": "B"
    }
  ]
}

I want to have:

{
  "userDetails": {
    "name": "DOM",
    "age": 30,
    "comments": [
      {
        "text": "Text"
      },
      {
        "text": "HELLO",
        "stuff": {
          "name": "DOM"
        }
      }
    ]
  }
  "items": [
    {
      "name": "A"
    },
    {
      "name": "B"
    }
  ]
}

So only denest the arrays with 1 element, and no more. Would love a solution using lodash folds.

Upvotes: 0

Views: 131

Answers (1)

user120242
user120242

Reputation: 15268

Simple tree walk and unwrap arrays length 1
Note: mutates in-place

data={
  "userDetails": [{
    "name": "DOM",
    "age": 30,
    "arr": [{"c":"c"}]
  }],
  "items": [
    {
      "name": [{"A": [[[["A"],["B"]]]]}]
    },
    {
      "name": "B"
    }
  ]
}

walk = (node,k) => {
    if(typeof node[k] === 'object')
    for(const key of Object.keys(node[k])) walk(node[k],key)
    if(Array.isArray(node[k]) && node[k].length === 1)
      node[k]=node[k][0]
}

walk({data},'data')

console.log(data)

Upvotes: 1

Related Questions