Guide on generating an array of objects using values nested within a parent object

I have multiple layers of objects nested within a main object like this:

var initialObj = { 
   firstKey: {
     x: true,
     y: 5
   },
   secondKey: {
     x: false,
     y: 10
   },
   thirdKey: {
     x: true,
     y: 15
   }
}

My goal is to extract an array of objects based on certain conditions within the nested objects. This array will also include the corresponding keys in a [key,value] format, similar to this:

resultingArray = [
  {
    x: true,
    y: 5,
    z: "firstKey" 
  },
  {
    x: true,
    y: 15,
    z: "thirdKey"
  }
]

Answer №1

To easily loop through the parentObj and extract specific data, you can utilize a for...in loop as demonstrated below:

var extractedData = [];
for(var property in parentObj){
   var obj = parentObj[property];
   if(obj.a) {
      extractedData.push({a: obj.a, b: obj.b, c: property });
   }
}

Answer №2

Firstly, it's important to note that

In JavaScript, associative arrays are not a native concept.

You can check out more information here.

In the provided example, "key1" is duplicated. If you wish to store data like this, then you need to use an Array, especially if one of the values in the nested objects holds the value true.

var parentObj = {
   key1: [
       {
         a: true,
         b: 2
       },
       {
         a: false,
         b: 2
       }
   ],
   key3: [
       {
         a: true,
         b: 2
       }
   ]
};

To achieve what you want, make use of the following approach:

var parentObj = {
   key1: [
       {
         a: true,
         b: 2
       },
       {
         a: false,
         b: 2
       }
   ],
   key3: [
       {
         a: true,
         b: 2
       }
   ]
};
var myArray = [];
for(var key in parentObj){
   var childObj = parentObj[key];
   var res = childObj.filter(function(element){
       return  element.a == true;
   });
   for(ele in res){
       res[ele].c = key;
   }
   if(res.length > 0){
       // if you want any of element having true property
       myArray.push(res[0]);
   }
}
console.log(myArray);

Answer №3

Here is a concise solution: by extracting keys from the main object, we can iterate over them to create new objects and then filter out any falsy values:

const mainObject = { 
   key1: {
     a: true,
     b: 2
   },
   key2: {
     a: false,
     b: 2
   },
   key3: {
     a: true,
     b: 2
   }
};

const finalResult = Object.keys(mainObject)
    .map(key => (Object.assign({}, mainObject[key], {c: key})))
    .filter(({a}) => a);

console.log(finalResult);

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

HTML not being displayed in AngularJS Directive template

Check out my fiddle here, where I am trying to build a group of checkboxes. Everything works perfectly in the prototype, allowing me to include multiple groups that run independently. However, when I added the code to my app and inserted the html template: ...

gulp crisper breaks when there is a JavaScript error

When working on polymer elements, I rely on using vulcanize with gulp to separate js from html files. But I've run into a problem - if there's an error in the js, vulcanize stops running and disrupts the build process. I thought that vulcanize ju ...

Why is it not performing as expected when removing all non-numeric elements from the array?

let arr = [1, "5", 3, 27, undefined, { name: 'Steven' }, 11]; for (let i = 0; i < arr.length; i++) { if (typeof arr[i] !== 'number') { arr.splice(i, 1); } } console.log(arr); // result: [1, 3, 27, {…}, 11 ...

Using Google Maps API v3 to Convert User-Input Coordinates into LatLng Points

I'm a beginner when it comes to using Google Maps and I'm having trouble with turning coordinates input by a user into moving a marker on my map. The goal is for the marker to pan to the specific coordinates entered by the user. Unfortunately, my ...

What is the best way to assign the innerText/innerContent of a list with the values from a multidimensional array?

As a newcomer to JavaScript, I apologize if the code is not up to par. My goal is to allow users to select a state from a form and display 5 cities. This is the current code snippet: HTML with Bootstrap classes <div class="row row1"> <div class= ...

Using Jquery to drag and drop items into a specific target zone

Check out my Jquery code: $(".list").draggable({helper: 'clone', cursor: 'hand'}); $(".drop1").droppable({ accept: '.list', hoverClass: 'dropareahover', drop: function(ev, ui){ var targetId = $(this) ...

Steps for eliminating an element upon the second click:

I am faced with a challenge where I need to dynamically add elements to a container on the first click and delete them on the second click. I feel like I am complicating things unnecessarily and there must be a simpler and more elegant solution available. ...

The installation of the material ui package was unsuccessful

C:\Users\User\Desktop\client4>npm i @material-ui/icons npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] ...

Is there a way to fully break out of a .forEach loop that's nested within a function?

Here is the method I am currently working with: wordFormDirty = (): boolean => { var self = this; angular.forEach(self.word.wordForms, function (wf, key) { var wordFormNgForm = 'wordFormNgForm_' + wf.wordFormId if ...

Html code snippet: Trigger a popup message with custom content, then redirect to another

One of the requirements is to display a popup when a person clicks on a button (this functionality has been implemented using Html.ActionLink with older code; the popup will only show if a session variable equals a certain value, which has already been fig ...

Learning how to use Express.js to post and showcase comments in an HTML page with the help of Sqlite and Mustache templates

I am facing a persistent issue while trying to post new comments to the HTML in my forum app. Despite receiving various suggestions, I have been struggling to find a solution for quite some time now. Within the comments table, each comment includes attrib ...

Combine an array of objects that are dynamically created into a single object

Having trouble transforming the JSON below into the desired JSON format using JavaScript. Current JSON: { "furniture": { "matter": [ { "matter1": "Matter 1 value" }, { "matter2": "Matter 2 value" }, { ...

Automatically clear text input field after choosing a new radio button using jQuery

I am dynamically adding Radio button function RadioButton() { $.ajax({ type: "POST", url: "VPATransaction.aspx/SetRadioButton", data: "{}", contentType: "application/json; charset=utf- ...

"Ensure that all necessary fonts and assets are included in the development of your Vue component

At the moment, I am utilizing vue-cli-service build --target lib --name myLib [entry] to compile Vue into a component library for integration into other projects. Nevertheless, it only produces four files which are: dist/myLib.umd.min.js dist/myLib.umd. ...

What methods can I employ in Javascript to automatically display search results obtained from multiple HTTP search queries?

In my tampermonkey script, I am attempting to process an array of names by performing a search and printing the page for each one. The script runs automatically upon loading the page, hence the necessity of the if statement. $(document).ready(function(){ ...

Using Phoenix Channels and Sockets in an Angular 2 application: A comprehensive guide

My backend is built with Elixir / Phoenix and my frontend is built with Angular 2 (Typescript, Brunch.io for building, ES6). I'm eager to start using Phoenix Channels but I'm struggling to integrate the Phoenix Javascript Client into my frontend. ...

Is there a way to eliminate nested or parent objects from an array using JavaScript?

I am looking for a way to remove an object based on its id without using a MongoDB query. Instead, I want to remove the object from an array stored in a variable using a JavaScript function. For example, if I provide id=ObjectId("5b693e7ddd65ec16a46b7f82" ...

Master the Art of Transforming an Array into a Variable

Here is an example of an array: const [listArr, setLA]= useState([ { id: Math.floor(Math.random * 100000), data: "This is data 1", }, { id: Math.floor(Math.random * 100000), data: "This is data 2", ...

Having trouble retrieving data from fetch operation

Having trouble with pulling and displaying search results on the Left page using the SearchFilms component? The API key has been deliberately removed, making it difficult for beginners to figure out what to do. Where should we start? import React, {Fragm ...

Why is populating values in a numpy compound dataset so sluggish?

My numpy compound datatype is structured like this: mytype = numpy.dtype([('x', 'f8'), ('y', 'f8'), ('z', 'f8'))]) Despite the structure, inserting da ...