Transform an array into an object with a personalized key

Here is an example array:

let Given = [
  ["SRM_SaaS_ES,MXASSETInterface,AddChange,EN"],
  ["ASSETNUM,AS_SITEID,apple,ball"],
  ["mesa01,SDASITE,ball,cat"],
  ["ASSETNUM,AS_SITEID,cat,ager"]
];  

I want to organize the data in a specific way:

let needed = [{
    'SRM_SaaS_ES': 'ASSETNUM',
    'MXASSETInterface': 'AS_SITEID',
    'AddChange': 'apple',
    'EN': 'ball',
  },
  {
    'SRM_SaaS_ES': 'mesa01',
    'MXASSETInterface': 'SDASITE',
    'AddChange': 'ball',
    'EN': 'cat',
  },
  {
    'SRM_SaaS_ES': 'ASSETNUM',
    'MXASSETInterface': 'AS_SITEID',
    'AddChange': 'cat',
    'EN': 'ager',
  }
]

I attempted to extract the keys from the first array and assign them accordingly but faced challenges.

let firstArrayData: string = this.Given[0];
let data = firstArrayData[0].split(',');
console.log(JSON.stringify(data));//["SRM_SaaS_ES","MXASSETInterface","AddChange","EN"]

Answer №1

If you’re looking for a solution, consider this approach:

let Example = [
  ["SRM_SaaS_ES,MXASSETInterface,AddChange,EN"],
  ["ASSETNUM,AS_SITEID,apple,ball"],
  ["mesa01,SDASITE,ball,cat"],
  ["ASSETNUM,AS_SITEID,cat,ager"]
];

// Extract keys from the first sub array:
const keys = Example[0][0].split(",");

// Iterate over the remaining sub arrays:
const result = Example.slice(1).map(function(item) {
  // Split values from current item
  const values = item[0].split(",");
  
  // Create an object with key names and item values:
  const obj = {};
  keys.forEach(function(k,i) {
    obj[k] = values[i];
  });
  
  return obj;
});

console.log(result);

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

Whenever I try to upload a file using ajax in MVC, I consistently encounter a null Request.Files in action side

I am facing an issue with uploading an image using ajax mode in MVC. I have tried a method where everything seems to work fine in the JavaScript code - it gets the formdata and sends the ajax request to the controller correctly. However, in my controller, ...

Integrate PHP include files into a website without allowing direct access, then dynamically load them using jQuery AJAX

I am utilizing jQuery AJAX to load the content of about.php page into my index.php section in this manner: $('.nav a[href="#about"]').on('click', function() { $('main').load('../../layout/about.php'); }); The iss ...

Go back to initial value loaded from ajax when canceling the action

On my webpage, I have both a display view (using span) and an edit view (using input) visible to the user. The user can switch between these views using buttons. In the Display View, there is an Edit Button that allows the user to switch to the Edit View. ...

Ways to expand the `Array.prototype` from an external library in a Node.js environment

While enjoying my time on hackerrank with pure JavaScript, I decided to steer clear of extra arrays or math libraries, unlike the convenience of using python. My approach is robust, but now I'm considering utilizing sugar.js or underscore. I came acr ...

Tips for Extracting Data from JSON String in Automation Anywhere after Making a REST API Request

Can someone guide me on how to extract "item" details from the "searchResult" element in Automation Anywhere? I'm struggling with parsing a JSON string that was returned as part of a REST API call, and unlike UiPath, AA doesn't seem to provide an ...

What is the best way to save <div> tags to localStorage?

Currently, I am facing an issue with setting an array of items (divs) to Local Storage. My intention is for these elements to be displayed in the Ui when the page reloads. The function I have written checks if there is already an array stored with that nam ...

Need to capture click events on an HTML element? Here's how!

I am attempting to capture click events on an <object/> element that is embedding a Flash file This is the approach I have taken so far: <div class="myban" data-go="http://google.com"> <object class="myban" data="index.swf>">< ...

Arrange the items in a list in JavaScript in descending sequence

How to sort a list of records in JavaScript in descending order? var number; //dynamic number retrieved from API var test; //dynamic text retrieved from API for (var i; i <= accList.length; i++) { var odlist = 'you have :' + test + number ...

How to pass GetServerSideProps into Page component props in Next.js with custom _app.js

Having issues integrating GetServerSideProps into my Next.js app. Despite the network call successfully fetching data and generating the pageName.json, the response data is not being injected into the page props as expected. Below is a snippet of my page ...

Ensuring that a $(function() is consistently executed and does not diminish over time

Simply put, I am troubleshooting my website and in order for it to function properly, I need to include the following code: <script type="text/javascript"> $ (function() { RESPONSIVEUI.responsiveTabs(); }); </script> What I& ...

The ng-model remains empty even after the $parent has been defined

I've encountered an issue where assigning ng-model to a text area and an input does not update the models. It is mentioned that this could be due to using ng-if causing a different scope, and I should use $parent, but even that solution is not working ...

Struggling to eliminate nesting in a JSON array using PHP

Looking for assistance with flattening a JSON array that contains nested elements under the "DEMARCHE" key. The current code only returns a single output array, but there are multiple arrays within my JSON file. Any help would be greatly appreciated. _ Tha ...

React error: File undefined (cannot be exported)

Encountering an issue while attempting to follow a tutorial: src/components/MyApp.js Line 17:18: 'myApp' is not defined no-undef Search for the keywords to learn more about each error. This is what my myApp.js file contains: import React fr ...

Having issues with closing a div tag using $.after() function

This issue can be better understood with an example: http://jsbin.com/lavonexuse The challenge here is to insert a full-width row after a specific column (identified by the class .insertion-point) when "Insert Row" is clicked. The problem I'm facing ...

Deleting an item from an array in React Native when its ID already exists

In my React Native application, I have implemented a feature where users can select tags from a list. When they click on a tag, it is added to an array of item IDs. If the user clicks on a tag that is already in the array, I want to remove it. Currently, ...

Use jQuery to dynamically update a text field within a table row based on a selection from

My understanding of JS and jQuery is not very strong. This is the HTML Output I created using a foreach-loop: $('#ProjectOfferPosition0IsystemTypeVariantId').on('change', function () { var prices = []; prices[1] = 500.00; ...

Function for adding numbers in Javascript with currying

Can you help me solve this interesting problem? I need a javascript function that can return the sum of all arguments passed to it, even when called multiple times. I have identified different ways in which the function can be called - sum(1, 2, 3, 4); ...

Unable to change the color of the RaisedButton component in Material-UI

Struggling to alter the color of the material-ui RaisedButton with inline style customization using backgroundColor: '#fb933c', yet it continues to display the default color. ...

Triggering Leaflet's Mouseout function during a MouseOver event

I am working on a leaflet map project where I am dynamically adding markers. One of my goals is to have the marker's popup appear not only when clicked, but also when the user hovers over it. This is the code snippet I have been using: function mak ...

Building a personalized version with core-js

I am currently in the process of developing a custom build using core-js. Following the instructions provided, I initiated the following commands: npm i core-js && cd node_modules/core-js && npm i The process seemed to go smoothly. Then, ...