James Pavett
James Pavett

Reputation: 399

Iterating over Object of Objects to create Array

I have an Object containing more objects that I want to iterate over. The structure is like this:

Objects in Objects

Eventually, I want to create an array where the key of the parent object points to the value in the child object's title column, so I can post later to some PHP script, i.e, I want:

BusinessJustification => 'titleValue'
Contract => 'titleValue'
...

But I am really struggling to actually loop through the array.

I have tried the following two methods, and while I can loop over the parent object, I seem to be struggling to get access to the values in the child, they just show as the index position, or undefined respectively.

for (var fields in this.postData) {
    for (var columns in fields){
        console.log(columns['title']);
    }
}

for (var fields in this.postData) {
    for (var columns in fields){
        console.log(Object.entries(columns['title']));
    }
}

Any help would be appreciated, as I am really scratching my head, and have tried a few things online.

Upvotes: 0

Views: 53

Answers (1)

Shidersz
Shidersz

Reputation: 17190

I eventually want to create an array where the key of the parent object points to the value in the child object's title column.

You can't generate an array with those properties in Javascript like you do in PHP: An array in PHP is actually an ordered map. A map is a type that associates values to keys. But you can create a Javascript Object, or a Map. However, I believe the first options is the one you need if you are going to send data to some server-side PHP script.

I believe you are searching for this:

const postData = {
    BusinessJustification: {blur: true, title: "business-title", valid: true},
    Contact: {blur: true, title: "contact-title", valid: true},
    Department: {blur: true, title: "department-title", valid: true},
}

let newObj = {};

for (const field in postData)
{
  newObj[field] = postData[field].title;
}

console.log(newObj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Upvotes: 1

Related Questions