Creating an array dynamically by parsing a JSON object in Javascript

I am currently working with a JSON object that looks like this:

var testJSON = [
    { "AssetA": "asset_a", "AssetB": "asset_b" },
    { "AssetA": "asset_a", "AssetB": "asset_b" },
    { "AssetA": "asset_c", "AssetB": "asset_d" },
{ "AssetA": "asset_c", "AssetB": "asset_e" }];

My objective is to iterate through the object and add duplicate keys to a new array called usedAssets. I have written some code to achieve this:

var usedAssets = [];

for (var key in testJSON) {
    console.log("Current key: " + key + " " + "value: : " +  testJSON[key].AssetA);
    console.log("Current key: " + key + " " + "value: : " + testJSON[key].AssetB);

    // check if in array
    if ((isInArray(testJSON[key].AssetA, usedAssets) || isInArray(testJSON[key].AssetB, usedAssets))) {
        break;
    }
    else {
        usedAssets.push(testJSON[key].AssetA);
        usedAssets.push(testJSON[key].AssetB);
    }
}
console.log(usedAssets);



function isInArray(value, array) {
    return array.indexOf(value) > -1;
}

However, the output I get is an array with only asset_a and asset_b. The usedAssets array should actually contain asset_a, asset_b, and asset_c. Ultimately, my goal is to determine at the end of the loop how many times each unique asset was used.

Answer №1

To find the occurrence of each element in an array and each property in an object, you can iterate through both and keep a count.

var testJSON = [{ "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_c", "AssetB": "asset_d" }, { "AssetA": "asset_c", "AssetB": "asset_e" }],
    count = {};

testJSON.forEach(o => Object.keys(o).forEach(k => count[o[k]] = (count[o[k]] || 0) + 1));

console.log(count);
console.log(Object.keys(count).filter(k => count[k] > 1));
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES5

var testJSON = [{ "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_c", "AssetB": "asset_d" }, { "AssetA": "asset_c", "AssetB": "asset_e" }],
    count = {};

testJSON.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        count[o[k]] = (count[o[k]] || 0) + 1;
    });
});

console.log(count);
console.log(Object.keys(count).filter(function (k) {
    return count[k] > 1;
}));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

This code snippet showcases a method to extract unique values from an array by reducing it to only the values that have been seen.

    var exampleArray = [
        { "ItemA": "item_a", "ItemB": "item_b" },
        { "ItemA": "item_a", "ItemB": "item_b" },
        { "ItemA": "item_c", "ItemB": "item_d" },
    { "ItemA": "item_c", "ItemB": "item_e" }];

    var seenValues = {};
    var uniqueValues = exampleArray.map(function(data){
      return Object.keys(data).map(function(key){
        return data[key];
      })
    }).reduce(function(prev, current) {
      return prev.concat(current);
    }, []).filter(function(item){
      if (!seenValues[item]){
          seenValues[item] = 1;
          return true;
      }
      seenValues[item] += 1;
      return false;
    })

    console.log('Seen Values: ' + JSON.stringify(seenValues));
    console.log('Unique Values: ' + uniqueValues);

Answer №3

It appears that you are attempting to tally how many times each asset was utilized... One straightforward approach is to maintain a map of previously seen objects. Using Array.prototype.reduce can help with this.

var testJSON = [{"AssetA":"asset_a","AssetB":"asset_b"},{"AssetA":"asset_a","AssetB":"asset_b"},{"AssetA":"asset_c","AssetB":"asset_d"},{"AssetA":"asset_c","AssetB":"asset_e"}];

var usage = testJSON.reduce((prev, next) => {
  prev[next.AssetA] = next.AssetA in prev ? prev[next.AssetA] + 1 : 1;
  prev[next.AssetB] = next.AssetB in prev ? prev[next.AssetB] + 1 : 1;
  return prev;
}, {});
console.log('How much were they used?', usage);
// If you want to know which ones were used two or more times, you can use
console.log('Used more than once', Object.keys(usage).filter(key => usage[key] > 1))
   

An alternative way without using reduce would be as follows:

var usage = {};
testJSON.forEach(el => {
    usage[el.AssetA] = el.AssetA in usage ? usage[el.AssetA] + 1 : 1;
    usage[el.AssetB] = el.AssetB in usage ? usage[el.AssetB] + 1 : 1;
});
console.log('How much were they used?', usage);
// If you want to know which ones were used two or more times, you can use
console.log('Used more than once', Object.keys(usage).filter(key => usage[key] > 1))

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

What is the process for transferring information from HTML to Python and then receiving the output in HTML?

I am completely unfamiliar with the connection between HTML and Python, so I am reaching out for some assistance. I hope that someone here can lend me a hand. Currently, my HTML is hosted on an Apache server, and I access the website using the address "". ...

What is causing Angular to show undefined when using an object?

I'm relatively new to Angular development. I am currently working on a controller that involves validating user input for registration. svs.controller('registrationCtrl', function($scope, validatorService) { $scope.$watch("registrationFor ...

What steps should I take to resolve issues with the npm installation on Linux?

I'm encountering an issue while attempting to use npm install in order to install a package. Despite my attempts to update and re-download from the root directory, I am unable to resolve the error. hackathonday1-2 git:(save-button) ✗ npm install f ...

Yii2 - JSONP response is failing to display any content and is not functioning properly, unlike JSON which is working perfectly

Having been programming for some time and familiar with the basics of Yii2, I am struggling to find documentation on Yii2 JSONP responses. Most resources only focus on returning JSON responses without any mention of JSONP. I initially referenced the Yii C ...

Encountering an issue with state setting - Experiencing an excessive amount of re-renders in a

If you want to see the solution in action, check out the Code Sandbox link provided below for better clarity on the issue at hand. Currently facing an issue with setting my mymoviegenreobjects as the mymoviegenreinfo state within the useFetchMovieGenreRes ...

The conversion of an org.json.JSONObject type to a JSONArray within an Android JSONObject is not possible

I am currently working on extracting data from a JSONObject that includes an array of user details. My current task involves retrieving the username from this json object. If you would like to view the JSON data, please click here. So far, I have succes ...

How can I align two inner boxes vertically in the most efficient manner?

.dd{ height:100px; width:100%; border:1px soild red; background:#000; } .dd .d1{ height:20px; width:20px; border:1px solid green; display:inline-block; } .dd .d2{ height:20px; width:20px; border:1px solid green; display:inl ...

Tips for utilizing jQuery to substitute strings within a content variable?

$content = "Please locate the student results where Date of birth **IS BETWEEN** 2012-02-18 00:00:00 AND 2013-02-18 00:00:00 AND name **IS NOT EQUAL TO** 'John' AND marks **IS BETWEEN** 40 AND 75 AND grade **EQUAL TO** 'A' AND AGE **I ...

Tips for adjusting the border color of a MUI Select field

https://i.stack.imgur.com/rQOdg.png This MUI select box changes color from blue to black based on selection. The challenge is to customize the text and border color to white (currently set as blue). Any suggestions on how to achieve this? ...

In my Vue project, I am required to extract only the numerical value from a select option text and disregard the rest of the text

Currently, I am in the process of learning Vue and have taken on the task of creating a basic tax calculator. The challenge is to display the result in real-time without requiring a "show total value" button. Everything seems to be functioning well except ...

Using Vuex: Bypassing Action and triggering Mutation directly within Component

When working with a vue.js app and utilizing vuex as the state management store, one may need to update a property's value in vuex. This can be achieved through two methods: One can dispatch an action method, which will then commit a mutation to a ...

displaying a confirmation alert upon unchecking a checkbox using javascript

I am trying to implement a feature where a message saying "are you sure?" pops up when the user tries to uncheck a checkbox. If they choose "yes", then the checkbox should be unchecked, and if they choose "no" it should remain checked. I'm new to Java ...

Using Python, transform a bash string into a JSON object

I have a key value pair that I need to export from my bash script where the following python code is integrated. Below is an excerpt from the bash script: output_test="ip:192.168.1.150,status:up" export output_test Python code embedded within the bash sc ...

Using jQuery to follow a div while scrolling that halts at a designated top or bottom boundary

I've been working on this jsfiddle: https://jsfiddle.net/3ncyxnzt/ Currently, the red box stops at a specified margin from the top of the page but I want it to also stop before reaching the bottom, so that it doesn't go under or over the footer. ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Having trouble fetching JSON on the server (NodeJs) as I keep receiving the error "Unexpected Token U in position 0"

I have gone through several posts on dealing with sending and retrieving JSON using NodeJs and Express, but I am still struggling to make it work. Someone mentioned that the issue might be due to invalid JSON. var arr = { City: 'someplace', Coun ...

Inspect the properties of a ReactJS component using Playwright

I'm relatively new to end-to-end (E2E) testing. One area I am looking to test involves changing the shipping address and automatically setting it as the billing address. For example, if I input Grove Street as my shipping address, I want it to mirror ...

Encountering an excessive number of re-renders due to attempting to display a FlatList component

I am attempting to showcase a flatList of numbers similar to this: (view image example) In order to achieve this, I created an array of objects with a numberName and a key using a loop: const number = 5; let [numbers, setNumbers] = useState([]); let nums ...

Developing a Fresh Entry on Monday.com Using Python

Is there a way to use Python to add a new item on Monday specifically on a Monday? I am working with a board that has multiple columns which need to be filled. How can I select a particular column and input a value into it? def ADD_data(api_key:str) -> ...

Numerous Levels of Dropdown Menus

I am looking to implement a feature on a web page where users can select multiple vehicles using JQuery. The idea is that selecting the brand in the first dropdown will populate the second dropdown with the models available for that specific brand. The ...