Utilize lodash to trim the object key

I am looking for a solution to remove occurrences of the object key y_ and achieve an output similar to useroutput:

var user =[{"data":"2","y_data1":1},{"data":"4","y_data1":3,"y_data2":3}]
var useroutput=[{"data":"2","data1":1},{"data":"4","data1":3,"data2":3}]

If you know of any methods using lodash or plain JavaScript, please share them with me.

Answer №1

Utilize lodash#map to change each element in the user array and employ lodash#mapKeys for transforming the keys of each item in the user array.

const result = _.map(user, data => 
  _.mapKeys(data, (v, k) => k.replace(/^y_/, '')));

const user = [
  {"data":"2","y_data1":1},
  {"data":"4","y_data1":3,"y_data2":3}
];

const result = _.map(user, data => 
  _.mapKeys(data, (v, k) => k.replace(/^y_/, '')));

console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Pure JS alternative: Utilize Array#map for transforming elements, and a combination of Object.entries() along with Array#reduce to alter the keys.

const result = user.map(data =>
  Object.entries(data).reduce(
    (r, [k, v]) => (r[k.replace(/^y_/, '')] = v, r),
    {}
  )
);

const user = [
  {"data":"2","y_data1":1},
  {"data":"4","y_data1":3,"y_data2":3}
];

const result = user.map(data =>
  Object.entries(data).reduce(
    (r, [k, v]) => (r[k.replace(/^y_/, '')] = v, r),
    {}
  )
);

console.log(result);
.as-console-wrapper{min-height: 100%; top: 0}

Answer №2

Utilizing vanilla JavaScript instead of lodash, you can achieve the desired result by using array.map, array.reduce, and a regex pattern to identify the target key. Take a look at the example below:

var users = [{"data":"2","y_1":1},{"data":"4","y_1":3,"y_2":3}]; 

console.log(users.map(obj => 
  Object.keys(obj).reduce((acc, elem) => {
    acc[elem.replace(/^y_/, "")] = obj[elem];
    return acc;
  },
{})));

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

Preventing data binding for a specific variable in Angular 2: Tips and tricks

How can I prevent data binding for a specific variable? Here's my current approach: // In my case, data is mostly an object. // I would prefer a global solution function(data) { d = data; // This variable changes based on user input oldD = da ...

implementing conditional logic in angularjs expressions

<p>{{isExisted}}</p> Looking to show either "Active" or "Inactive", but the isExisted variable only returns true or false. Need help with setting up a conditional if else statement to change it to the desired value. ...

Updating the parent page host within a cross-domain iframe: issues encountered in Firefox and Chrome browsers

I am encountering an issue with my iframe app where I am receiving an alert indicating "-error" in Chrome related to top.location.href. jQuery.ajax({ type : 'get', url : 'check_if_fb_data_set.php', success ...

Using JavaScript (AJAX), learn the process of incorporating XML data within HTML files

I'm relatively new to HTML and I'm attempting to create a self-contained HTML page that includes all necessary CSS, data, and JavaScript within the file itself. While I understand that this will result in a rather messy HTML document, it is essen ...

Decoding JSON string List<string> data in a JsonResult MVC

Having trouble deserializing a JSON string to MyModel and receiving an "Error" from my AJAX call: $.ajax({ type: 'POST', traditional: true, url: '/Employee/Extract', ...

The jQuery Validate Plugin only validates emails when the user moves away from the input field

Resolved: Upon inspecting my version of jquery-validate.js, I discovered that it was missing the onkeyup handler. Despite using version 1.12 Opre, which should have had this functionality according to its Github history from 2013, it seemed like there may ...

Troubleshooting date format errors when parsing two parameters in a jQuery AJAX request

Does anyone have advice on how to make an ajax call with two parameters - number and date? I encountered the following error: Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given in... Here is the HTML code involved: <di ...

Bootstrap Collapse function might not function properly immediately following the execution of Collapse Methods

Here is the reference link: http://jsfiddle.net/72nfxgjs/ The code snippet I used is from w3schools: http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_collapse&stacked=h <script type="text/javascript"> $("#collapse1").col ...

Executing PHP include statement with ajax: A step-by-step guide

I am trying to achieve a feature on my website where when a button is clicked in the index.php file, an AJAX request will load about.php and display it inside a div tag within index.php. Unfortunately, my current code doesn't seem to be working as exp ...

Update the objects with new values when the user makes changes in the

I am working with dynamically created input fields const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data {navtive?.map((item, index) => { return ( <input type="text" name={item.id} ...

If IE's conditional comments are dysfunctional

Could this be a silly question? I feel puzzled by it. I've been using an if IE conditional statement to address some issues in IE6. In the head section, this is what I have: <!--[if lt IE 7] > <script type="text/javascript" src="js/ie6.js" ...

Is there an improved method for toggling animations in CSS using jQuery compared to my current approach?

Looking to create a toggle effect for a dropdown box that appears and disappears when a button is clicked. var clickState = false; $("#show").on("click", function() { if (!clickState) { $(".animated").removeClass("off"); refreshElement($(".an ...

javascript - Include new parameter in object literal and retrieve

I have a base object that I define using an object literal: var obj = { key1 : 'value1', key2 : 'value2' } Now, I want to pass this object to a function and extend it like this: myFunction( obj + { key3 : 'value3' ...

Error encountered while trying to update a record using NodeJS, Express, and MySQL modules due to SQL syntax

When attempting to update a MySQL record in NodeJS, I encounter an "app crashed" error in Visual Studio Code's terminal. app2.js: const express = require('express'); const mysql = require('mysql'); // establish connection cons ...

JavaScript function encountered an error due to an expected object

Currently, I am in the process of developing an application using VS2015, JavaScript, Angular, and MVC 5. Here is an excerpt of my JavaScript code: var myApp = angular.module('QuizApp', []); myApp.controller('QuizController', [&apos ...

Tips for integrating material UI sample snippets into a component

I have a specific goal in mind: to create a page with a header that says "Survey Start" followed by a user selection interface. My vision is to implement a simple component as follows: export class Survey extends Component { state = { } ren ...

Interactive World Map with Fluid Motion Animation built using HTML, CSS, and JavaScript

I am in need of an uncomplicated way to visually represent events taking place around the globe. This involves creating a 2D image of a world map, along with a method to show visual alerts when events occur at specific geographical coordinates [lat, lng]. ...

Changing the templateUrl of a directive on the fly using the controller

How can I dynamically pass the templateUrl for the app_modal directive from the "ServerController" controller to allow for different templates for different modals? I have included the URL as an attribute in the "app-modal" tag used in the server_group.htm ...

Looking to showcase elements within an array inside an object using ng-repeat

In this JSON dataset, we have information about various anchoring products. These products include anchors, cleats, snubbers, shackles, and more. When it comes to displaying these products on an HTML page using Angular, make sure to properly reference the ...

Whenever I am building a React application, I encounter a bug that states: "node:fs:1380 const result = binding.mkdir()"

Whenever I try to enter the command: create-react-app my-app --template typescript I keep encountering this error message: node:fs:1380 const result = binding.mkdir( ^ Error: EPERM: operation not permitted, mkdir 'D:\ ...