Retrieving individual property from JSON with an array of values provided

Is there a way to extract names from the provided JSON, based on an array of IDs?

[
   {
      "id": 0,
      "name": "salesTransNo"
   },
   {
      "id": 1,
      "name": "terminalNo"
   },
   {
      "id": 2,
      "name": "salesTransDate"
   },
   {
      "id": 3,
      "name": "salesTransTime"
   },
   {
      "id": 4,
      "name": "exceptionAmount"
   },
   {
      "id": 5,
      "name": "laneNumber"
   }
]

The desired outcome is to have an array containing only the names from the JSON data, given an array of id values.

For example: array of ids: [2, 4, 5]

The expected output should be:

["salesTransDate", "exceptionAmount", "LaneNumber"]

How can this be achieved using Lodash or JavaScript?

I attempted to use _.find and _.map to retrieve only the name from the result. However, it seems to work only for a single value input, rather than an array like [2, 4, 5].

Answer №1

To get the desired property, first filter the objects and then extract the wanted property.

var dataset = [{ index: 0, title: "salesTransNo" }, { index: 1, title: "terminalNo" }, { index: 2, title: "salesTransDate" }, { index: 3, title: "salesTransTime" }, { index: 4, title: "exceptionAmount" }, { index: 5, title: "laneNumber" }],
    indices = [2, 4, 5],
    output = dataset
        .filter(({ index }) => indices.includes(index))
        .map(({ title }) => title);

console.log(output);

Answer №2

Working with Vanilla JavaScript:

const data = [
   { "id": 0, "name": "salesTransNo" },
   { "id": 1, "name": "terminalNo" },
   { "id": 2, "name": "salesTransDate" },
   { "id": 3, "name": "salesTransTime" },
   { "id": 4, "name": "exceptionAmount" },
   { "id": 5, "name": "laneNumber" }
];

const indexes = data.map(item => item.id);

const id = 4; // Desired data.id item
const selectedName = data[indexes.indexOf(id)].name;

If you need to retrieve multiple results, you can create a function like this:

function getNamesFromData ( idsList ) {
   const result = [];
   idsList.forEach(id => {
      const indexes = data.map(item => item.id);
      const selectedName = data[indexes.indexOf(id)].name;
      result.push(selectedName);
   });
   return result;
}

getNamesFromData([2, 4, 5]); // Returns ["salesTransDate", "exceptionAmount", "laneNumber"]

Note: Error handling is omitted for simplicity. It's advisable to handle cases where indexOf() returns -1.

Answer №3

let elements = [{
    "id": 0,
    "name": "orderNumber"
  },
  {
    "id": 1,
    "name": "customerName"
  },
  {
    "id": 2,
    "name": "orderDate"
  },
  {
    "id": 3,
    "name": "totalAmount"
  },
  {
    "id": 4,
    "name": "deliveryAddress"
  },
  {
    "id": 5,
    "name": "paymentMethod"
  }
]

let selectedElements = elements.filter(elements => [1, 3, 5].includes(elements.id));

for (let item of selectedElements)
{console.log(item.name);}

Answer №4

To achieve this, you can utilize lodash's chain method by incorporating _.keyBy(), _.at(), and _.map():

var data = [{ id: 0, name: "salesTransNo" }, { id: 1, name: "terminalNo" }, { id: 2, name: "salesTransDate" }, { id: 3, name: "salesTransTime" }, { id: 4, name: "exceptionAmount" }, { id: 5, name: "laneNumber" }];
var ids = [2, 4, 5];

var result = _(data)
  .keyBy('id') // transform into a dictionary based on id
  .at(ids) // retrieve items with matching ids from the array
  .map('name') // extract the names
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer №5

To find the common elements between two arrays, you can utilize the lodash#intersectionWith method. Remember to pass the collection first, followed by the IDs and finally the comparator function.

var result = _.intersectionWith(data, ids, (a, b) => a.id == b);

var data = [{
    id: 0,
    name: "productCode"
  }, {
    id: 1,
    name: "productName"
  }, {
    id: 2,
    name: "category"
  }, {
    id: 3,
    name: "price"
  }],
  ids = [1, 3];
  
var result = _.intersectionWith(data, ids, (a, b) => a.id == b);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

Assigning a value to an Angular class variable within the subscribe method of an HTTP

Understanding the inner workings of this process has been a challenge for me. I've come across numerous articles that touch on this topic, but they all seem to emphasize the asynchronous nature of setting the class variable only when the callback is t ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

Troubleshooting: Stage element not being recognized by Angular and CreateJS

I'm currently working on an Angular view that inherits from an ng-view element. Within the view file, there is a canvas that is controlled by a specific controller. My goal is to bring up a stage that allows me to add elements onto the canvas. Howev ...

How is it that the callback method in the subscribe function of the root component gets triggered every time I navigate between different pages within the application?

I am currently using Angular 10 and have developed a server that returns an observable: export class CountrySelectionService { private _activeCountry = new BehaviorSubject(this.getCountries()[0]); public getActiveCountryPush(): Observable<CountryS ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...

Having trouble enabling push notifications on Android with ngCordova

Having trouble with push notifications through the ngCordova plugin. Followed the sample code from (with a slight change - no deviceready listener, code inside ionicPlatform.ready listener) Below is the code snippet: angular.module('myApp', [& ...

Reveal concealed content when a responsive table becomes scrollable on a mobile device

I recently completed a project that was overloaded with tables. I made all the tables responsive, but they still take vertical scroll if they don't fit on certain devices due to their varying widths. For instance, Table A requires vertical scroll o ...

Utilizing Sinon.js in Node.js to conduct unit tests on Postgres interactions

I am struggling to figure out how to use sinon to mock a call to postgres that is required by the module I am testing. I'm not sure if it's even possible. I'm not trying to test the postgres module itself, just my object to ensure it's ...

Testing React JSX components using ES6 unit tests

Currently, I am utilizing React, JSX, ES6, and Karma. I am facing an issue with my code. Can anyone pinpoint what might be wrong? I am attempting to execute a test using Karma-Runner but encountering some obstacles: let React = require("react") ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

Troubleshooting script error: Dealing with Ineffective Redirects

I am currently using a JavaScript code that allows users to jump to a directory by typing its name. Here is how it functions: If the input field is left empty, the user will be directed to a page called "error.html" which displays the message "This field ...

Is it possible to retrieve data from a particular index within an array using Mongoose

For instance, if the following is my documents: { "field": [ "hello", "random wording", { "otherId": 3232, "otherId2": 32332 } ], } Would it be possible to create a query that matches both i ...

When the phone locks, Socket.io experiences a disconnection

setInterval(function(){ socket.emit("stayalive", { "room": room }); }, 5000); I have developed a simple browser application with an interval function that is currently running on my phone. I am using Chrome on my Nexus 4 for debugging purposes. However, ...

Unable to retrieve event data and integrate it into HTML using jQuery

Just starting out with leaflet and JavaScript, jQuery. I've got an index.html page displaying a map, and want to show the coordinates of the mouse pointer underneath the map when it moves. To achieve this, I have a div element with the id "coordinat ...

Which should take precedence: EffectComposer or Z-Buffers in rendering?

Currently, I am in the process of constructing a network graph through the use of Three.js, which involves creating numerous nodes and connecting lines. My main objective is to ensure that the lines always appear behind the nodes, particularly because the ...

What's the best way to adjust the width of the <Input> component in Reactstrap?

How can I adjust the width of an input element in Reactstrap to be smaller? I've attempted to set the bsSize to small without success <InputGroup> <Input type="text" name="searchTxt" value={props.searchText ...

Refreshing Angular 4 route upon modification of path parameter

I have been struggling to make the subscribe function for the params observable work in my Angular project. While I have successfully implemented router.events, I can't seem to get the subscription for params observable working. Can anyone point out w ...

A Guide to Implementing Schema.virtual in TypeScript

After switching from using schema.virtual in JavaScript to TypeScript, I encountered an error when trying to use it with TypeScript. Below is my code: UserSchema.virtual('fullname').get(function () { return `${this.firstName} ${this.lastName}` ...

Tips for creating animated navigation buttons that guide users to specific sections within interior pages

Recently, a client approached me with an interesting challenge: They want a homepage design that features the navigation loading in a specific location. However, once a user clicks on one of the nav buttons, they would like the entire navigation to anima ...

Using React - How to access prop values within child menus of Ant Design Dropdown

I have a feed of posts similar to a Facebook timeline, where each post has a dropdown menu with options for "edit, delete, report". Using the Ant Design UI library, I encountered an issue where I couldn't access the prop value "DeleteId" within the c ...