Merging distinct objects/values in AngularJS/Javascript to create a straightforward list

I possess a dynamically generated, multi-level nested object containing DISTINCT values. My goal is to flatten it (using either AngularJS or vanilla JS) and produce a straightforward array or object for each key/value pair. For example, if the object takes this form:

[ 

{name : "parent",
 age: 21,
 children: [
     { name : "child",
     dob: [{
         day: "01",
         month: "01",
         year : "82"
     }],
     children: [
     { 
        name : "grandchild",
        dob: [{
            day: "01",
            month: "01",
            year : "02"
            }]
      }
    ]
   }
 ]
}

];

The flattened object should resemble this structure:

"name":"parent",
"age":21,
"children.name":"child",
"children.dob.day":"01",
"children.dob.month":"01",
"children.dob.year":"82",
"children.children.name":"grandchild",
"children.children.dob.day":"01",
"children.children.dob.month":"01",
"children.children.dob.year":"02"

I have come across 2 functions to flatten an object, but both add indexes alongside every node. (0.children.0.children.0.dob.0.year) This does not serve my purpose, as my values are unique. I require the format specified above. You can view the functions in use within this codepen: https://codepen.io/anon/pen/qMXEmB

Is there anyone who can assist me in eliminating those bothersome "zeros" from my final object?

Answer №1

Savage, however, in place of

toReturn[i + '.' + x] = flatObject[x];

You could eliminate the zeros in this manner:

let index = i === "0" ? '' : i + '.';
toReturn[index + x] = flatObject[x];

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

Tips on adding an array value to the XPath syntax while conducting a search in Selenium IDE

As a novice in Selenium, I might not be articulating my query clearly. I am working with Selenium IDE version 3.17.0 and attempting to validate the presence of device names on a web page under test. These device names are stored in an array: execute scrip ...

Show a row of pictures with overflow capabilities

I am looking to develop my own image viewer that surpasses the capabilities of Windows. My goal is to design an HTML page featuring all my images laid out horizontally to maximize screen space. I also want the images to adjust in size and alignment as I z ...

Is it considered acceptable to perform roughly 100 queries on the Android SQLite database for the purpose of storing a single data item?

I have recently incorporated SQLite data storage into my Android translator app. The current situation is as follows: the app receives translations in JSON format from a server, then proceeds to parse it and build an object tree consisting of 50 to 100 obj ...

Using MongoDB and NodeJS to retrieve data from a promise

When I make a request to the database using promises, my goal is to extract the values of "latitude" and "longitude" for all documents and store them in an array. This is how I am currently approaching it: const promises = [ dbo.collection("users").f ...

The error mentioned above was encountered within the <App> element: specifically in the App component

I recently started the Knowthen Go/React tutorial and am encountering some difficulties with React. When I attempt to launch my application, I encounter this error and I can't seem to pinpoint the cause. Here is the link to my GitHub repository where ...

Searching for a solution to eradicate and " from a JSON value in Apache Nifi?

After invoking the Rest API, I received a JSON flowfile response which includes data on different offers: { "data": [ { "description": "\n\n\"s, lorem Epsom jdfg\n\"", " ...

Error: Type Error - 'style' is not defined in the Progress Bar Project

Having recently started learning Javascript, I have been engaging with various tutorials and projects in order to gain familiarity with the language. One particular tutorial that caught my attention is a Progress-Bar tutorial by "dcode" available at this l ...

Properties of the State Object in React Redux

I'm curious as to why my state todos were named todo instead of todos in the redux dev tools. Where did that name come from? There is no initial state, which makes me wonder. I'm currently following a Udemy course by Stephen Grider, but I am wor ...

Passing the JSON object located at the selected index within a listview to the next activity in my android application

Hello everyone, I need some help with a coding issue I'm facing. I have been searching for a solution to this problem but haven't been successful so far. In theory, I know that I should use i.putExtra("jsonArray", jArray.toString()); in my inte ...

Using the power of AJAX, retrieve data from a PHP script and showcase the response within

Within my HTML file, I have implemented a feature that allows users to input a value. To validate this input, I created a PHP script that checks if the entered value exists in the database. The script returns the following JSON response: {"active":true} ...

What changes occurred to module file names following the process of minification?

I'm currently troubleshooting an issue with this particular code snippet: import globalComponents from './global-components'; // ... globalComponents.forEach((component) => { // eslint-disable-next-line no-underscore-da ...

Having trouble accessing Kotlin JS from JavaScript

I'm currently experiencing an issue where I am unable to call any Kotlin JS function and receiving an error stating that 'something' is not defined. Initially, I attempted compiling the project with Gradle but found success after following ...

Unable to detect click event in Vue devtools

My component is supposed to detect if a menu item has a submenu and toggle its visibility accordingly. However, when I click on it, nothing happens and no event is registered in the Vue devtools. Despite following the Vue docs closely and using the same sy ...

Combining jQuery methods and selectors within a loop

Can a sequence of selectors and methods be generated within a loop? For instance, assuming an array of elements is given: array[0] = '.type1value1, .type1value2, .type1value3'; array[1] = '.type2value1, .type2value2, .type2value3'; ar ...

Error encountered when attempting to run an Angular 2 application with 'ng serve' command

Initially, I installed angular-cli using the command npm install -g angular-cli and then proceeded to create an angular-cli project. Following that, I used the command ng new Angular2TestProject to create a project and changed the directory to Angular@Test ...

Setting up routeProvider in MVC4 with WebAPI2I will walk you through the process

I have a unique app that displays a dynamic calendar with various events. Upon clicking on an event, my goal is to effortlessly showcase detailed information below the calendar. The URLs for each event are created using a loop and look like this : &apos ...

Using AngularJS $http.jsonp() method to interface with Google Maps Distance Matrix API

I am currently working on integrating the Google Maps Distance Matrix API into my project to calculate distances between two points using specific coordinates. My implementation involves AngularJS and the $http.jsonp() method to make requests to the API: ...

Searching for a value within an array of objects using JavaScript: The ultimate guide

Similar Question: Locate specific object by id within a JavaScript objects array What is the best way to determine if a value exists in a given JavaScript array? For instance: var arr = [ {id: 1, color: 'blue'}, {id: 2, colo ...

Using .change(); in JavaScript code with jQuery does not trigger a function

Here we have a generic code example for a jQuery function: $(document).ready(function() { if (something) { // This does something } else if (something else) { // This does something else } else { // And this does somethin ...

NodeJS closes the previous server port before establishing a new server connection

During my development and testing process, whenever I make changes, I find myself having to exit the server, implement the updates, and then start a new server. The first time I run the command node server.js, everything works perfectly. However, when I m ...