Changing JSON information into a Javascript Array utilizing knockout

I have a JSON Array that includes various rules and values, but I want to convert it into a specific array format. Here is an example of the original JSON Array:

AccessToFinancialServicesRule: {Clean: 3, Copy: 3}
BoardParticipationRule: {Clean: 3, Copy: 3}
Documents: null
EconomicDevelopmentRule: {Clean: 3, Copy: 3}
EmployeeStructureRule: {Clean: 3, Copy: 3}
EmpowermentFinanceRule: {Clean: 3, Copy: 3}
EnterpriseDevelopmentRule: {Clean: 3, Copy: 3}
OwnershipRule: {Clean: 3, Copy: 3}
PreferentialProcurementRule: {Clean: 3, Copy: 3}
ResponsibleSocialMarketingRule: {Clean: 3, Copy: 3}
SkillsDevelopmentRule: {Clean: 3, Copy: 3}
SocioEconomicDevelopmentRule: {Clean: 3, Copy: 3}
SupplierDevelopmentRule: {Clean: 3, Copy: 3}

The goal is to convert it into the following array:

0: {label: "Ownership", clean: 3, copy: 3}
1: {label: "Skills<br>Development", clean: 3, copy: 3}
2: {label: "Localisation", clean: 3, copy: 3}
3: {label: "Socio-Economic<br>Development", clean: 3, copy: 3}
4: {label: "Board Participation", clean: 3, copy: 3}
5: {label: "Employee Structure", clean: 3, copy: 3}
6: {label: "Preferential Procurement", clean: 3, copy: 3}
7: {label: "Enterprise Development", clean: 3, copy: 3}
8: {label: "Supplier Development", clean: 3, copy: 3}

Each item in the new array should have a label key and display the values of clean and copy.

However, when I try to achieve this using a JavaScript function, the result is not as expected. Instead of separate items, everything is combined into one object. Here is the code snippet I used:

var allItems = [data.Mappings];
            var testData = allItems.map(function(item){
                return {
                    'label': item,
                    'clean': item.Clean,
                    'copy': item.Copy 
                };
            });

            console.log(testData)

But this approach doesn't work as intended, and the output is like this:

0:
clean: undefined
copy: undefined
label: {OwnershipRule: {…}, BoardParticipationRule: {…}, SkillsDevelopmentRule: {…}, EmployeeStructureRule: {…}, PreferentialProcurementRule: {…}, …}

I can't figure out what I'm doing wrong here. Any suggestions?

Answer №1

If you want to access properties in objects, you should utilize the Object.keys method. Here's a simple example to demonstrate this:

const convertToArray = array.map((item) => {
  const key = Object.keys(item)

  if (item[key]) {
    return {
      label: key[0],
      clean: item[key].Clean,
      copy: item[key].Copy
    }
  }
})

To see the complete code example, click on this link: https://jsfiddle.net/qgwxbuem/

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

Exploring connections among Array Objects on a Map

Here are some JSON examples of Pokemon Battles: [ { "battleID": "1", "trainers": [ { "LastName": "Ketchum", "ForeName": "Ash" }, { "LastName": "Mason", ...

If other options fail, Else If may not be a suitable choice

This is the process: switching from Issue: x==0||1 to x==0||x==1 etc. This code runs from an .html file <body> <div class="" id="pimg1"> </body><script> var x=new Date().getMonth(); if (x == 0||x == 5||x == 2){docu ...

jQuery is consistently lagging one step behind when calculating the sum with keypress

I am currently working on developing a calculator that adds up the values entered with each key press. Here is the code snippet I have been using: $('#padd').keypress(function() { var ypoints = "200"; var points = parseInt( $(th ...

What could be causing ng-repeat to malfunction?

My ng-repeat is not working with the table - only the header part is being displayed in the output. I have checked my binding and it seems to be correct, but I know I am missing something. Can someone please help me figure out what I am doing wrong? JAVA ...

The success of a jquery ajax call always seems to elude me as it consistently throws

I've been facing an issue with my code snippet. The problem lies in the fact that the function on success is never executed; instead, it always triggers the error section. $.ajax({ url: 'http://localhost/zd/get_list', data: 'ter ...

Submit form in a new tab and refresh the current page

It seems like my mind is hitting a roadblock, I'm having trouble finding a better solution for this particular issue: I need to send a form via POST method (with data handling on the server) and have it open in a new tab with a custom URL containing ...

Aligning Content in the Middle of a Bootstrap Column

Can anyone help me with centering the content of a bootstrap column vertically? I'm facing an issue when setting width: 100% and height: 100% for the overlay div. Any solutions? Here is an example image of what I am trying to achieve: https://i.ssta ...

Guide on Minimizing ES6 with Gulp

I am new to creating a gulpfile.js manually for my project based on Backbone and Marionette. My initial gulp file had the following structure: var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var browserify = require ...

Ways to maintain the integrity of external values?

As a newcomer to Python, I may have some naive questions. I am attempting to create a program that generates a two-dimensional array. One function populates a list and returns an array, while a second function takes the results of the first function and or ...

Implementing Pagination for JSON Requests in jQuery

How do I enable pagination in my JSON parsing script? function appendPost(__, post) { var title = $('<div/>') .addClass('post_title') .text(post.post_title); var content = $('<div/>') .addClass(&a ...

Creating a JSON Object from Query Result in SQL Server

I'm currently working with Azure SQL Server and attempting to export the results of a query in a specific format. Desired Query Result: { "results": [{...},{...}], "response": 0 } Reference Example: https://msdn.microsoft.com/en-us/library/dn9218 ...

Easy way to make a jQuery getJSON request to Twitter

After browsing through numerous Twitter and jQuery related questions, I have yet to find a solution to my specific issue. My goal is simple - to retrieve 5 "tweets" from a public user. At this stage, I am not manipulating the data in any way, but for some ...

I am struggling to parse a specific JSON file

A json file contains a variable number of elements that describe keywords. Here is an example: {"keywords":[{"keyword":"halloween","score":0.9621220167107003}, {"keyword":"pumpkin","score&quo ...

Having trouble resolving a setInterval problem with JavaScript?

Yesterday, I learned about the setInterval function which allows me to execute a task or function after a specific amount of time. While I have successfully implemented the interval in my code, it keeps adding new lines with the date each time. What I re ...

Show a message of 'no results found' when implementing a jQuery plugin for filtering items in a list

I recently implemented the 'Filtering Blocks' tutorial from CSS-Tricks to filter items by category on an events website I'm developing. While the filtering functionality works perfectly, I realized that there is no mechanism in place to sho ...

Incorporating HTML5 Video Using an AJAX Request

I am attempting to fetch a video using an ajax query, but it seems that the video player control buttons are missing. Here is the code I am using: $.ajax({ context: document.body, url: "/?get=json&act=video", type: "get", success: fu ...

Automatically format text fields to display time in hh:mm format from right to left as you type

Is there a way to automatically format hh:mm as the user types in a text field? The default format is 00:00, and I would like it to fill the minutes part when the first two characters are entered, followed by filling the hour part with the third and four ...

Guide to leveraging clsx within nested components in React

I am currently using clsx within a React application and encountering an issue with how to utilize it when dealing with mappings and nested components. For instance: return ( <div> <button onClick={doSomething}>{isOpened ? <Component ...

Looking to display user data within a specific div using JavaScript? Check out my code!

Issue Solved by Me I resolved the problem by using ko.js to check data binding in java! Thanks to everyone who helped. I have implemented this code to display online users in my chat application (x7chat 3, available for free download) The code can be fou ...

Is there a way to prevent Prettier from automatically inserting parentheses for a single argument in an arrow function?

Currently, I've integrated Prettier into my workflow, but I've encountered an issue with arrow functions in JavaScript. For example: arg => console.log(arg) However, Prettier automatically formats it as: (arg) => console.log(arg) This for ...