A guide on extracting the value of a key from an object in angularjs

I stored the data in an object like this:

$scope.modelName = {
    name: {}
};

The data was saved as {"APPLE":true,"ORANGE":true}. I am attempting to retrieve only the keys and save them in another object using a for loop. However, I'm having trouble getting the desired result.

for (var i = 0; i < 2 ; i++) {        
    $scope.fruitRulesRules.push({
        field: "fruitName",
        subType: "equals",
        value: Object.Keys($scope.modelName.name[i])
    });
}

Appreciate any assistance on this matter.

Answer №1

Object.keys() function is used to return an array of the keys within the object. It's important to correctly select the key when looping through. While your attempt was close, it didn't quite hit the mark.

Check out this demo on jsfiddle: http://jsfiddle.net/pzky9owf/1/

var modelName = {
        name: {
            APPLE: true,
            ORANGE: true
        }
    },
    fruitRulesRules = [];

for (var i = 0; i < 2; i++) {
    fruitRulesRules.push({
        field: 'fruitName',
        subType: 'equals',
        /*
            This part was almost there. You could also consider storing Object.keys in a separate variable to avoid recalculating in each iteration if it doesn't change frequently.
        */
        name: Object.keys(modelName.name)[i]
    });
}

console.log(fruitRulesRules);

UPDATE: And just a quick note, you should be using Object.keys with a lowercase k, not uppercase as seen in the fiddle example.

ANOTHER UPDATE: As pointed out by @KrzysztofSafjanowski in another comment, the order of keys returned by Object.keys() is not guaranteed, so while the above approach may work, it might not always yield the expected results.

I've made changes to the fiddle to demonstrate an alternative method that doesn't rely on key order: http://jsfiddle.net/pzky9owf/2/

Answer №2

It seems like there may be an issue with how you are accessing the key. Does this provide any clarity for you?

Object.keys({"APLLE":true,"ORANGE":true})[0] //outputs "Apple"

One possible solution could be:

Object.Keys($scope.modelName.name)[i]

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

Enhancing Material UI KeyboardDatePicker with personalized CSS design

Material UI KeyboardDatePicker is the component I'm currently using. https://i.sstatic.net/It50L.png In order to remove the black line visible in the datepicker (as shown in the screenshot), what steps should I take? Displayed below is the code ...

The execution of the code may encounter errors initially, but it generally runs without any issues on subsequent attempts

I recently developed a piece of code to ascertain whether a value in the database is null or not. Here's the snippet: var table; var active = false; function CheckActive(table){ this.table = "table" + table + ""; var db = window.openDatabas ...

Angular, JavaScript, and PHP are three powerful programming languages that

This file contains HTML code <ul class="list"> <li id="numword" data-score="{{item.score}}" class="" ng-repeat="item in words track by $index"> {{item.word}} {{item.score}} </li> </ul> Here is the visual representa ...

JS : Removing duplicate elements from an array and replacing them with updated values

I have an array that looks like this: let arr = ['11','44','66','88','77','00','66','11','66'] Within this array, there are duplicate elements: '11' at po ...

What is the best way to cancel a request within an HTTP-interceptor?

Within an application, I have established the following URL structure for the API: // public public/url-xyz // private dashboard/url-xyz To avoid unnecessary requests, what is the most effective method for canceling a request? My current approach involv ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

Connecting specific choices with corresponding information

I have an object called item, which has a property named department_id that corresponds to an array of objects known as departments. My goal is to create a dropdown menu in a form where I can choose a department and update the id to item.department_id. Cur ...

App for registering for an AngularJS course

Currently, I am developing an application that involves a JSON list containing information about various courses such as title, course ID, location, and type. One of the features in my app includes a modal window that appears when a user clicks on a speci ...

The Benefits of Semantic Class Names compared to Microdata

As I strive to use semantic class names, my exploration of microdata and SEO raises a question: Is it necessary to use both? Compare these two HTML snippets representing an event: Using CSS classes: <div class="event" itemscope itemtype="http://schema ...

ng-repeat continuing to render within ng-if even when the ng-if condition is false

In my Angular application, I am using an ng-repeat directive to iterate over an array of objects. Each object in the array has a property called type and an array called contents. Depending on the type of the object, I want to display the contents array di ...

Launching a centered pop-up window to display a submitted form message

I am attempting to create a page that displays a confirmation message in a center-aligned pop-up window after the user submits a form. I have managed to open the page in a pop-up window, but I am struggling to center the window using my current code (I pre ...

The transition of a controlled input to an uncontrolled state within a component, along with a partial update to the state

In my project, I have a main component that needs to collect a list of contacts including their name and email: import { useState } from 'react' import AddContactFn from './components/AddContactFn' function App() { const [contacts, ...

Utilizing npm/buffer package within a TypeScript module

I'm interested in implementing this NPM package: https://www.npmjs.com/package/buffer I'm unsure about how to convert this line of code into typescript: var Buffer = require('buffer/').Buffer Could you provide me with the correct code ...

Clicking on a list item in React's material design will illuminate the item, marking it

I have 2 panels with a list group on each panel, following material design guidelines. Concern: When clicking the first list-item on panel 1, it does not get selected and change to style = "success", or highlight the selected item. The same issue occurs ...

What is the best way to store selected items from a multi-select box in AngularJS that is generated using ng-repeat?

I have a scenario where I need to handle a group of select boxes instead of just one. Each select box holds a different option, and when the user changes their selection, I want to save that value in a variable or an array. I've managed to do this for ...

Axios failing to include Content-Type in header

I have set up an Odoo instance in the backend and developed a custom module that includes a web controller. Here is the code for the web controller: Web Controller # -*- coding: utf-8 -*- from odoo import http import odoo from odoo.http import Response, ...

Tips for implementing conditional app.use() in nestJS backend strategies?

Trying to incorporate helmet into my nestJS application. I also require the inclusion of graphqlUploadExpress. How can I properly utilize the usesUpload condition to implement either helmet alone or along with upload? import { NestFactory } from '@nes ...

Clicking on the expand button will render the content inside the <p:panel>

My current frontend using JSF loads an excessive amount of data, not always necessary for the user. This data is categorized by tags and I want it to be rendered dynamically with a click on an expand panel: <p:panel header="#{myBean.someStringT ...

What is the best way to showcase a specific column from a dataset using Vue.js and axios?

Hey there, I'm still getting the hang of all this and haven't quite mastered the jargon yet. Here's what I need help with: I managed to retrieve data from my SQL database using axios, and when I check in (f12) - network - preview, it shows: ...

Struggling to Keep Track of Namespaces within an Array

Creating a chat application with multiple namespaces allows users to discuss different topics of interest, like 'dogs' or 'cats'. In my initial version, I stored each namespace in a variable and it worked perfectly: Server side: var ...