Using the spread operator in combination with the reduce function in JavaScript

I am attempting to generate all possible paths of the provided JSON object. I have managed to generate the paths, but I would like the final array to be flattened without any nested arrays inside it. I tried spreading the array, but there are still some nested arrays in the final result. My goal is to have all elements in a flat structure.

Current output:

[
  "obj",
  "level1.level2.level3.key",
  [
    "arrayObj.one[0].name",
    "arrayObj.one[0].point"
  ]
]

Expected output:

[
  "obj",
  "level1.level2.level3.key",
  "arrayObj.one[0].name",
  "arrayObj.one[0].point"
]

Below is the code snippet that I tried:

const allPaths = (obj, path = "") =>
  Object.keys(obj).reduce((res, el) => {
    if (Array.isArray(obj[el]) && obj[el].length) {
      return [...res, ...obj[el].map((item, index) => {
        return [...res, ...allPaths(item, `${path}${el}[${index}].`)];
      })];
    } else if (typeof obj[el] === "object" && obj[el] !== null) {
      return [...res, ...allPaths(obj[el], `${path}${el}.`)];
    }
    return [...res, path + el];
  }, []);

const obj = {
  obj: 'sample',
  level1: {
    level2: {
      level3: {
        key: 'value'
      }
    }
  },
  arrayObj: {
    one: [{
        name: 'name',
        point: 'point'
      },
      {
        name: 'name2',
        point: 'point2'
      },
      {
        name: 'name2',
        point: 'point2'
      }
    ]
  }
}

console.log(allPaths(obj));

Answer №1

UPDATE: I initially misunderstood the question, but now I understand it correctly. The code below will effectively solve your issue.

You need to flatten your object using dots as separators.

If that's what you're looking for, the following code should do the trick:

const obj = {
  obj: 'sample',
  level1: {
    level2: {
      level3: {
        key: 'value'
      }
    }
  },
  arrayObj: {
    one: [{
        name: 'name',
        point: 'point'
      },
      {
        name: 'name2',
        point: 'point2'
      },
      {
        name: 'name2',
        point: 'point2'
      }
    ]
  }
}

function flattenData(data, prefix) {
  let result = {}
  for(let d in data) {
    if(typeof data[d] == 'object') Object.assign(result, flattenData(data[d], prefix + '.' + d))
    else result[(prefix + '.' + d).replace(/^\./, '')] = data[d]
  }
  return result
}

console.log(flattenData(obj, ''))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...

SQL Server 2016 is throwing an error due to syntax issues with 'JSON'

After recently installing SQL Server 2016 CTP3 for its JSON output feature, I attempted to use it in my SQL Query following the example provided on MSDN. However, when using the keyword JSON in my query, it did not turn blue and instead gave an error messa ...

Jade Compilation with Gulp

Currently utilizing gulp-jade, I have encountered an error with a particular template: 557| 558| > 559| 560| .tabs-wrap(ng-show="eventExists"): .contain-center 561| 562| #room-tabs-contain.contain-disable.contain: .contain-center unexpec ...

Generate with different HTML elements

This is a simple React code snippet: var Greetings = React.createClass({ render: function() { return <div>Greetings {this.props.name}</div>; } }); ReactDOM.render( <Greetings name="World" />, document.getElementB ...

Calculate the frequency of a specific name within a Json Array

I am looking to calculate the frequency of occurrences in a JSON Array returned by an API. Here is my data: data = [ {"id":"1939317721","pauseReason":"DISPLAY","DeptName":"Account"}, {"id":"1939317722","pauseReason":"DISPLAY","DeptName":"Admission"}, ...

What are some techniques for managing scrolling within a particular element?

I am currently working with Vue.js and utilizing Element UI components. I want to incorporate a scroll management function to achieve infinite scrolling. To better understand, please refer to the screenshot in the Example section: Despite trying differen ...

Extract individual data elements from an HttpResponse

When making a request to the Google Geolocation API, the JSON results are returned in the following manner: Sample (I apologize for the unformatted JSON) {"geocoded_waypoints" : [ { "geocoder_status" : "OK", "place_id" : "EiQ3LCA3IExha2VzaWRl ...

What are some ways to conceal the API connection within a button?

I have a code that allows me to perform a certain API call with a link. Here is an example: <a class="btn btn-default" href="https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey='.$user.'&Password='.$pass.'&Domain=&ap ...

Retrieving complete credit card information with the help of JavaScript

I've been grappling with extracting credit card data from a Desko Keyboard, and while I managed to do so, the challenge lies in the fact that each time I swipe, the card data comes in a different pattern. Here is my JavaScript code: var fs = require ...

Initiate an "execute.document" command directly from the address bar

While reviewing my old website, I stumbled upon this snippet: <input type="image" id="QuickPass" name="QuickPass" src="/images/QuickPass.gif" alt="Quick Pass" onclick="document.pressed=this.value" value="QuickPass" /> nestled within this form: & ...

Tips on sending multiple values to AngularJS Directive

Currently, I am in the process of creating a simple AngularJS directive. As I am still very new to AngularJS, I would appreciate it if the answers provided could be simplified! The directive I am working on is essentially a combobox. For those unfamiliar ...

Converting a C# Dictionary to a JSON object with WCF and HTTPSerialization

Recently delving into the realm of WCF services using HTTP Routing, I find myself confronted with a challenge. The services in my new project return objects adorned with [DataContract] and [DataMember] attributes, presented as part of services marked with ...

Changing the context results in the entire component being re-rendered

Currently, I am encountering a challenge where I have two different components within my Layout.js component that need to "share" props with each other. To address this issue, I introduced a ContextProvider named IntegrationProvider. However, a new proble ...

The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `se ...

Vue alert]: The element "options" is not declared in the current instance but is being referenced during the rendering process. Facing problem with Vue JS

Encountering an error while rendering the project. I've thoroughly checked all details but couldn't pinpoint which line is causing the issue. The console displays the following warning: Vue warn]: Property or method "options" is not defined on th ...

Unable to display parsed JSON data on Android device

I'm having trouble displaying a JSON string generated by a PHP file on an Android TextView. Can anyone help me figure out why? public class AllUsersActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON ...

Utilize jQuery to extract data from a Steam page in JSON format

Although I have researched extensively on this topic, it is still not functioning as desired. I came across this Steam page in JSON format. My aim is to extract the lowest_price variable without using PHP as I am incorporating it into my Chrome extension. ...

Optimizing json data transformation in R

Using R to process zigbee2mqtt log files is a common task that I tackle regularly. head(data) [1] "info 2024-03-11 14:08:01: MQTT publish: topic 'zigbee2mqtt/TempBadEG', payload '{\"battery\":17,\"humidity ...

Extract JSON data from a string with an undetermined character encoding

My current challenge involves extracting HTML content from websites and converting it into JSON format, with the need to manage various character encodings. After researching, I have learned that if the encoding is not utf-8, it is most likely ISO-8859-1. ...

Having trouble with the jQuery each function's functionality

I am creating circular counters for surveys by generating a counter for each answer option. Currently, I am utilizing this "plugin": Issue: The problem lies in the plugin not fetching the text value from the <div> element and failing to draw coun ...