JavaScript: Streamlining the Selection of Objects in an Array

I'm completely new to JavaScript, and I've hit a roadblock with a task. I'm hoping someone can help guide me through it.

The challenge I am facing involves working with an Array of Objects structured like this:

var labels = [
            // labels for page 1
            {pageID:1, labels: [
                {labelID:0, content:[{lang:'eng', text:'Txt1 Eng'}, {lang:'de', text:'Txt1 De:'}]},
                {labelID:1, content:[{lang:'eng', text:'Txt 2 Eng:'}, {lang:'de', text:'Txt2 De:'}]},
                {labelID:2, content:[{lang:'eng', text:'Txt 3 Eng:'},{lang:'de', text:'Txt 3 De:'}]}
            ]},

            // labels for page 2
            {pageID:2, labels: [
                {labelID:0, content:[{lang:'eng', text:'Txt1 Eng'}, {lang:'de', text:'Txt1 De:'}]},
                {labelID:1, content:[{lang:'eng', text:'Txt 2 Eng:'}, {lang:'de', text:'Txt2 De:'}]},
                {labelID:2, content:[{lang:'eng', text:'Txt 3 Eng:'},{lang:'de', text:'Txt 3 De:'}]}
            ]}
    ]

My objective is to create a function that will return an array of labels (Objects) for a specific page and language. By calling this function with pageID as 1 and lang as eng, I want to generate an array like the following:

var desiredArray = [
    {labelID:0, text:'Txt1 Eng'}, 
    {labelID:1, text:'Txt1 Eng'}, 
    {labelID:2, text:'Txt2 Eng'}
] 

Currently, I am working on writing the function to retrieve/build the new array:

this.getLabelsForPageAndLang = function (numPage, lang) {
            // This section filters the main object and selects the object with pageID == numPage
        var result = labels.filter(function( obj ) {
            return obj.pageID == numPage;
        });

        var tempResult = result[0].labels;
        var desiredResults = [];  // Here I aim to store the new objects
        for (var i=0; i<tempResult.length; i++) {
            var simpleLabelObject = {};
            simpleLabelObject.labelID = tempResult[i].labelID;
            // simpleLabelObject.text = ?????

            results[i] = simpleLabelObject;
        }

        console.log (results);

    };

...But how do I access the correct value (corresponding to the selected language) in the content property?

Answer №1

To keep the matching page, you can utilize the filter method in a similar manner as shown below.

this.findLabelsForPageAndLanguage = function (pageNumber, language) {
        // This section filters the main object and selects the object with pageID equal to pageNumber
    var filteredResult = labels.filter(function(obj) {
        return obj.pageID === pageNumber;
    });
    
    var contentFilter = function(obj){ return obj.lang === language};

    var tempResults = filteredResult[0].labels;
    var desiredLabels = [];  // Store new objects here
    for (var i=0; i<tempResults.length; i++) {
        var labelObject = {};
        labelObject.labelID = tempResults[i].labelID;
        var matchContent = tempResults[i].content.filter(contentFilter);
        labelObject.text = matchContent[0].text;

        desiredLabels[i] = labelObject;
    }

    console.log(desiredLabels);

};

No boundary checks were implemented assuming there is always a matching element in your code, but it may be advisable to include them.

If you wish to avoid creating two closures each time the function is called, you can prototype an object like so:

var LabelFilter = function(pageNumber, language) {
    this.pageNumber = pageNumber;
    this.language = language;
};

LabelFilter.prototype.filterByPage = function(obj) {
    return obj.pageID === this.pageNumber;
}

LabelFilter.prototype.filterByLanguage = function(obj) {
    return obj.lang === this.language;
}

LabelFilter.prototype.filterLabels = function(allLabels) {
    var result = allLabels.filter(this.filterByPage, this);

    var tempResults = result[0].labels;
    var desiredLabels = [];
    for (var i=0; i<tempResults.length; i++) {
        var labelObject = {};
        labelObject.labelID = tempResults[i].labelID;
        var matchedContent = tempResults[i].content.filter(this.filterByLanguage, this);
        labelObject.text = matchedContent[0].text;

        desiredLabels[i] = labelObject;
    }

    return desiredLabels;
}

console.log(new LabelFilter(1, "eng").filterLabels(labels));

Answer №2

Let's filter once more:

const extractLabels = (pageNumber, language) => {
    // This function filters the main object to select the object with pageID equal to pageNumber
    const result = labels.filter(obj => obj.pageID === pageNumber);
    const tempResults = result[0].labels;
    const desiredResults = []; // New objects will be stored here
    for (let i = 0; i < tempResults.length; i++) {
        let simpleLabelObj = {};
        simpleLabelObj.labelID = tempResults[i].labelID;
        const lg = tempResults[i].content.filter(lg => lg.lang === language);
        simpleLabelObj.text = lg[0].text;

        desiredResults.push(simpleLabelObj);
    }

    console.log(desiredResults);

};

http://jsfiddle.net/4r7tE/

Answer №3

An example of a 'secure' method to handle situations where pages share the same pageID and have multiple contents in the same lang:

this.retrieveLabelsForPageAndLang = function(pageNumber, language) {
    var output = [];
    var matchedPages = labels.filter(function(item) {
        return item.pageID === pageNumber;
    });
    for (var p = matchedPages.length - 1; p >= 0; p--) {
        var currentPage = matchedPages[p];
        for(var i = currentPage.labels.length - 1; i >= 0; i--) {
            var labelIdentifier = currentPage.labels[i].labelID;
            for (var j = currentPage.labels[i].content.length - 1; j >= 0; j--){
                if (currentPage.labels[i].content[j].lang === language) {
                    output.push({labelID: labelIdentifier, contentText: currentPage.labels[i].content[j].text});
                }
            }
        }
    }    
    console.log(output);
}

Code Sample: http://jsfiddle.net/6VQUm/

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

Avoid adding any empty entries to the list using jQuery

I have implemented a code to prevent any blank entries from being added to my list, and it seems to be working fine. However, I can't shake the feeling that there might be a better way to achieve this. Even though it functions correctly, it doesn&apos ...

Exploring mysterious traits through inheritance

In my Angular and TypeScript project, I have defined an interface: export interface A { name: string; } Now I have two other interfaces that inherit from interface A: export interface B extends A { year: number; } export interface C extends A { ...

"Encountering an issue with Next.js where the Redux

Hey there, I'm working on a simple project using Nextjs. I need to access the state of my Redux store but I'm encountering an error when trying to use store.getState, it's throwing an error saying getState is undefined. Additionally, I have ...

What is the correct way to utilize the karma-ng-html2js-preprocessor?

I'm working on a directive called stat24hour: angular .module('app') .directive('stat24hour', stat24hour); function stat24hour(req) { var directive = { link: link, template: 'scripts/widgets/templ ...

I'm curious as to why a webpage tends to load more quickly when CSS files are loaded before script files. Can anyone shed some

While watching a video, I came across some concepts that were a bit difficult for me to grasp. The video mentions that scripts are 'serialized' and can block subsequent files from loading. According to this explanation, Script 1 would load first ...

Error: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

Is there a way for me to fetch the post variables sent through $http.post in Angular within my Node.js backend?

My front end code looks like this. auth var time = 5; $http.post('/tasks/addTime', null, { headers: { Authorization: "Bearer " + auth.getToken() }, data: { id: "Me", time: time, } }); This is the back e ...

What is the proper way to invoke a method within the same class, Class A?

I'm facing an issue where I need to call the method getData() inside my AJAX function again if a 401 status occurs and the counter is less than or equal to 1. However, for some reason, the method is not being called in that particular scenario. How ca ...

Mastering the Art of Destructuring within React Components

After extensive research online, I still struggle to fully grasp destructuring, although I'm getting there. //before destructuring function me(details){ console.log('My name is ' + details.name + ' and I work for ' + details.com ...

Tips for transferring data from an HTML textbox to a JavaScript variable

I'm currently working on a form that fetches data from a database and dynamically stores it in a table. There's a button labeled "add" which, when pressed by the user, adds a new row to the table. I also have a hidden counter that keeps track of ...

Identify the geometric figure sketched on the canvas using the coordinates stored in an array

After capturing the startX, startY, endX, and endY mouse coordinates, I use them to draw three shapes (a line, ellipse, and rectangle) on a canvas. I then store these coordinates in an array for each shape drawn and redraw them on a cleared canvas. The cha ...

Successfully converted Javascript variables to PHP variables, however, I faced difficulties when attempting to compare the PHP variable

When transferring a javascript variable to a php variable, it is typically done using POST or Ajax methods. The code below shows a way to convert the javascript variable to a php variable without relying on POST, Get, or Ajax. When the php variable ...

Utilize the Bootstrap column push-pull feature on the mobile version of

https://i.stack.imgur.com/yTBIt.png When viewing the desktop version, div A is displayed at the top of the page. However, I would like to move it to the bottom when viewing on a mobile device (col-xs). I have attempted to solve this issue myself without s ...

Troubleshooting Problems with Fancybox Scaling on Small Landscape-Oriented Mobile Devices

Issue Description: In my responsive web design, I am utilizing Fancybox v2.1.5. The problem arises when smaller mobile devices with a more rectangular shape than square are used. In portrait orientation, when invoking Fancybox, it expands to the width of ...

Having trouble getting the onClick event to trigger in ReactJS buttons

The buttons are not functioning as expected, allowing for the addition of positive, neutral, or negative feedback. Interestingly, when I added a default button using different syntax to add negative feedback, it worked. This suggests that there may be an ...

Having trouble with document.getElementById.innerHTML not displaying the correct content?

document.getElementById works in getting the element, but for some reason, the content disappears as soon as it is written in it. There are no errors on the console to indicate what's causing this behavior. I have been unable to identify the reason b ...

Algorithm for Generating Cubes

My current task involves working with a dynamically generated array of cubes, each having its distinct position and color. These cubes are situated on a 5x5 field, where each cube is connected to at least one other cube. Now, I am looking to introduce a ne ...

Is there a potential security flaw in jQuery when using $.get(code_url) to execute the returned code without relying on eval() or appending it to the DOM

As I was debugging my NodeJS application, I stumbled upon a surprising discovery: when using jQuery with a simple $.get(code_url) where code_url is a URL leading to server-side JavaScript code, the code gets executed. The expected behavior should be: $.g ...

Experiencing difficulty decoding JSON output on jquarymobile's HTML page when making an Ajax request

After developing screens for my Android application using PhoneGap and jQuery Mobile, I have included the necessary JavaScript and CSS files in my HTML page: <link rel="stylesheet" href="css/jquery.mobile-1.3.1.css" /> <script src="js/jquery-1. ...

Interactive JQuery calendar

Can anybody assist me with this issue? I am seeing question marks in the graphic and I'm not sure why. I remember encountering these symbols before and I believe it has something to do with charset. Currently, I am using: <meta http-equiv="Content ...