A guide to implementing child level filtering of JSON data with Lodash

Here is a JSON dataset I am working with:

[
  {
    "campaignId": 111,
    "campaignCategory": "Diabetes",
    "result": [
      {
        "campaignType": 1,
        "name": "tes1"
      },
      {
        "campaignType": 1,
        "name": "test22"
      },
      {
        "campaignType": 3,
        "name": "test33"
      }
    ]
  },
  {
    "campaignId": 222,
    "campaignCategory": "Orthopedic",
    "result": [
      {
        "campaignType": 1,
        "name": "Orthopedic"
      }
    ]
  },
  {
    "campaignId": 333,
    "campaignCategory": "Cardiology",
    "result": [
      {
        "campaignType": 3,
        "name": "Cardiology"
      },
      {
        "campaignType": 1,
        "name": "Cardiology 123"
      }
    ]
  }
]

I tried the following filter but it did not return the desired data:

_.filter(summary, function (data) {
 return (post, _.filter(data.result, {'campaignType': 3}));

I am looking to obtain the following data after applying the filter:

[{ campaignId: 111, campaignCategory: 'Diabetes', result: [{
  campaignType: 3, name: 'test33'
}] }, 
{ campaignId: 333, campaignCategory: 'Cardiology', result: [{
  campaignType: 3, name: 'Cardiology'
}] } ];  

Only nodes with campaignType: 3 are displayed in the filtered result. Either a Lodash or pure JavaScript solution will be suitable.

Answer №1

To identify objects in an array that contain a specific item with a designated value and then add them to a new array, you can utilize the reduce method. In this case, the requirement is to search for objects with a .result property where the campaignType is equal to 3:

const findOutput = () => {
  const outputList = arr.reduce((accumulator, item) => {
    const results = item.result.filter(({ campaignType }) => campaignType === 3);
    if (results.length) {
      accumulator.push({ ...item, result: results });
    }
    return accumulator;
  }, []);
  console.log(outputList);
};

const arr = [{
    campaignId: 111,
    campaignCategory: 'Diabetes',
    result: [{
      campaignType: 1,
      name: 'tes1'
    }, {
      campaignType: 1,
      name: 'test22'
    }, {
      campaignType: 3,
      name: 'test33'
    }]
  },
  {
    campaignId: 222,
    campaignCategory: 'Orthopedic',
    result: [{
      campaignType: 1,
      name: 'Orthopedic'
    }]
  },
  {
    campaignId: 333,
    campaignCategory: 'Cardiology',
    result: [{
        campaignType: 3,
        name: 'Cardiology'
      },
      {
        campaignType: 1,
        name: 'Cardiology 123'
      }
    ]
  }
];
findOutput();

Answer №2

If you want to optimize your code, consider filtering the inner result array first and then selecting the outer objects if any filtered elements exist. Afterwards, create a new object with the filtered result.

var data = [{ campaignId: 111, campaignCategory: 'Diabetes', result: [{ campaignType: 1, name: 'tes1' }, { campaignType: 1, name: 'test22' }, { campaignType: 3, name: 'test33' }] }, { campaignId: 222, campaignCategory: 'Orthopedic', result: [{ campaignType: 1, name: 'Orthopedic' }] }, { campaignId: 333, campaignCategory: 'Cardiology', result: [{ campaignType: 3, name: 'Cardiology' }, { campaignType: 1, name: 'Cardiology 123' }] }], 
    result = data.reduce((r, o) => {
        var result = o.result.filter(({ campaignType}) => campaignType === 1);
        if (result.length) r.push(Object.assign({}, o, { result }));
        return r;
    }, []);

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

Answer №3

In vanilla JavaScript, one way to filter and map data is by using the combination of filter and some along with map.

var data = [{ campaignId: 111, campaignCategory: 'Diabetes', result: [{
  campaignType: 1, name: 'tes1'
},{
  campaignType: 1, name: 'test22'
},{
  campaignType: 3, name: 'test33'
}] },
{  campaignId: 222, campaignCategory: 'Orthopedic', result: [{
  campaignType: 1, name: 'Orthopedic'
}] }, 
{ campaignId: 333, campaignCategory: 'Cardiology', result: [{
  campaignType: 3, name: 'Cardiology'
},
{
  campaignType: 1, name: 'Cardiology 123'
}]} ];


var res = data.filter(campaign => campaign.result.some(type => type.campaignType === 3));

res = res.map(campaign => {
        campaign.result = campaign.result.filter(type => type.campaignType ===3);
        return campaign;
      });


console.log(res);

Answer №4

To achieve the desired outcome, you can utilize a combination of Array.reduce and Array.forEach methods:

const data = [{ "campaignId": 111, "campaignCategory": "Diabetes", "result": [{ "campaignType": 1, "name": "tes1" }, { "campaignType": 1, "name": "test22" }, { "campaignType": 3, "name": "test33" } ] }, { "campaignId": 222, "campaignCategory": "Orthopedic", "result": [{ "campaignType": 1, "name": "Orthopedic" }] }, { "campaignId": 333, "campaignCategory": "Cardiology", "result": [{ "campaignType": 3, "name": "Cardiology" }, { "campaignType": 1, "name": "Cardiology 123" } ] }];

const result = data.reduce((accumulator, { result, ...rest }) => {
  result.forEach(item => item.campaignType === 3 ? accumulator.push({ ...rest, result: [item] }) : null);
  return accumulator;
}, []);

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

ActiveRecord::RecordInvalid: The validation process has failed: User entries must be valid

I am currently working on a project that involves seeding an sqlite3 database from a JSON file. The project includes two models: user and logins. require 'json' records = JSON.parse(File.read('db/people.json')) records.each do |rec ...

Is it possible to load babel-polyfill using <script async> tag?

I have created a modal dialog on my webpage that appears when certain interactions occur. Utilizing React, I used webpack to generate a compact bundle that can be added to my page using a script tag. Since it incorporates Generators and needs to support ...

Creating a C# Web API that Only Returns Values, Not Keys

I am currently developing a Web API using C#, and my goal is to only retrieve the values without the keys. I am fetching data from a DataSet and here is an example of what I have so far; { "Role": [ { "PersonName" ...

Developing typeScript code that can be easily translated and optimized for various web browsers

Can TypeScript alleviate the worry of having to use code such as this (especially when considering browsers like IE that may not support indexOf)? arrValues.indexOf('Sam') > -1 Does the transpiling process in TypeScript generate JavaScript c ...

Utilize Redux-forms to trigger an alternative submission method when ComponentWillRecieveProps is called

redux-forms version: 6.6.3 react version: 15.5.0 Seeking help with calling different submit functions from the componentWillReceiveProps method in a React component. componentWillReceiveProps(nextProps) { if (nextProps.updateTierConfigState == "Valida ...

javascript - determine whether a hyperlink has been accessed

Is there a method to determine if a link has been visited? In Firefox, the color of a link changes after clicking on it, which leads me to believe it is possible. Edit: This question pertains to a Firefox extension, so I am unable to modify the HTML or CS ...

What is the best way to change a date-containing string into a Json object?

I need to convert a string into a JSON Object using JavaScript. However, when I do so, the date in the original string gets completely changed. Here is the string I am working with: var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01- ...

Using an external JavaScript script may encounter difficulties when loading pages with jQuery

Trying to utilize jQuery for loading html posts into the main html page and enabling external scripts to function on them. Utilizing a script (load.js) to load posts into the index.html page: $(document).ready(function () { $('#header').loa ...

What is the process of connecting JSON keys to one another?

I am currently brainstorming a solution to link two distinct JSON formats with their respective keys. Here are the two formats: { "price": [ 511, 499, 419, 312 ], "paid": "OK", "contract": "year", "begindate": "01/01/2018", " ...

Embed a JSON within another JSON in Oracle 19 database management system

Hello, I am facing a particular issue. I am trying to generate a JSON object from a table that contains another JSON object within one of its columns. Here is the structure of the table: CREATE TABLE BRUNOVS.TABLA_JSON_1 ( COL CLOB COLLATE USING_NLS ...

What is the best way to retrieve the data stored in a TD element within a TR row in an HTML table?

How can I retrieve the value of a clicked table cell? https://i.stack.imgur.com/HfXBK.png <table id="table" class="table" style="margin-right: auto; margin-left: auto" > <thead> <tr> <th>Request Number</th> ...

Dealing with the element not present error in Protractor can be managed by using various

Is there a way to achieve similar Exception handling in Protractor as we can with Selenium webdriver in Java? When dealing with element not found exceptions, what is the most effective approach to handle them using Protractor? ...

Checking if the upload process has been completed using XMLHttpRequest Level 2

Currently, I am utilizing ajax for uploading files. Once the file has been uploaded, PHP needs to conduct a thorough check on it (including mime type, size, virus scan using clamscan, and more). This process can take a few seconds, especially for larger fi ...

AntDesign is throwing an error stating that resetFields is not a function when using

I'm facing an issue with resetting the fields in my form. The form allows users to add more forms, and so on... Upon successful validation, I want to save the data in my DB and store AND reset all input fields in the form. Unfortunately, I'm un ...

Storing JSON string values in String parameters: A beginner's guide

Does anyone have experience with storing JSON strings from Oracle MCS CustomAPI responses in separate String parameters to create data controls? { "Header": { "MessageID": "uE60F40847D", "ReplyTo": { "Address": "http:2005/08/addressing/ano ...

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

"Troubleshooting issue with AngularJS ng-repeat order by functionality based on

I am currently trying to sort my ng-repeat by descending date order, with the newest items appearing first. Despite my efforts, I have been unable to achieve this. I have carefully checked for any errors in quoting, but still no luck. I've attempted ...

There are no headers present in the response from apollo-client

I am currently utilizing a graphql api along with a vue.js frontend that incorporates the apollo client for fetching data from the backend. This setup has been operating smoothly thus far. In each response header, the server sends back a new JWT-Token whi ...

Disappearing input field in DateTimePicker Bootstrap when blurred

Currently, I am utilizing the Bootstrap DateTimePicker plugin to enable users to select a specific date and time. The plugin functions well with one minor issue - whenever the user clicks outside or loses focus on the calendar box, both the box itself and ...

Exploring ways to personalize the parsing of url query parameters in express.js

When using req.query, the hash of query parameters is returned. Additionally, if a parameter consists of a JSON object, it is automatically parsed into JSON format, which is quite impressive. However, I am curious about customizing this parsing process. I ...