logo
down
shadow

How to filter an array of objects based on another array of objects?


How to filter an array of objects based on another array of objects?

By : Damian Roszak
Date : October 18 2020, 06:10 AM
seems to work fine I have two array of objects like below , You could filter with a subset of conditions without ALL flag.
code :
var conditions = [{ condition: "Expert", value: "All" }, { condition: "Coach", value: "willaim" }, { condition: "manager", value: "Brandy Lovings" }, { condition: "site", value: "ALL" }, { condition: "client", value: "ALL" }],
    data = [{ Date: "11/6/2018", client: "Verizon", Expert: "Ellison, Lauren", Coach: "willaim", manager: "Brandy Lovings", site: "Sundance", Metric: "STR" }, { Date: "11/6/2018", client: "Amzaon", Expert: "Ellison, Lauren", Coach: "Dash Williamson", manager: "David", site: "abc", Metric: "STR" }],
    filters = conditions.filter(({ value }) => value.toUpperCase() !== 'ALL'),
    result = data.filter(o =>
        filters.every(({ condition, value }) => o[condition] === value));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Share : facebook icon twitter icon
Filter array of objects based on array of objects returns same results

Filter array of objects based on array of objects returns same results


By : Kolbe
Date : March 29 2020, 07:55 AM
wish helps you Just change your last part of code to the following then you can achieve
code :
for (let i in data) {
    cleanedData[i] ={}
    for (let key in keys) {
        if (keys[key] in data[i]) {
            cleanedData[i][key] = data[i][keys[key]];
        };
    }
}
console.log(cleanedData);
let data = [
    {
        "X": 1,
        "Y": 2,
        "Z": 3,
    },
    {
        "X": 4,
        "Y": 5,
        "Z": 6,
    },
    {
        "X": 7,
        "Y": 8,
        "Z": 9,
    },
];

let keys = {
    A: 'X',
    B: 'Y',
};
let keyChain = {};
let cleanedData = [];

// construct the placeholder key value pair array
for (let key in keys) {
    keyChain[key] = '';
}

// check keys to see if there's a match with the json
for (let i in data) {
    cleanedData[i] ={}
    for (let key in keys) {
        if (keys[key] in data[i]) {
            cleanedData[i][key] = data[i][keys[key]];
        };
    }
}
console.log(cleanedData);
JavaScript Filter array of objects based on property of another array of objects

JavaScript Filter array of objects based on property of another array of objects


By : kutub
Date : March 29 2020, 07:55 AM
Hope this helps filter is the right tool, but includes is not. The entries in tasks are objects, not strings; none of them will match any of the types in tests.
Instead, the simple version uses some to see if any entries in tasks match the type of the activity being tested:
code :
let tests = activities.filter(a => tasks.some(t => t.type == a.type));
const tasks = [
  {
    name: "test",
    type: "one"
  },
  {
    name: "test2",
    type: 'two'
  }
];
const activities = [
  {
    name: "test",
    type: "one"
  },
  {
    name: "test2",
    type: 'two'
  },
  {
    name: "test3",
    type: "three"
  }
];
 
let tests = activities.filter(a => tasks.some(t => t.type == a.type));
console.log(tests);
.as-console-wrapper {
  max-height: 100% !important;
}
const knownTypes = new Set();
for (const task of tasks) {
    knownTypes.add(task.type);
}
let tests = activities.filter(a => knownTypes.has(a.type));
const tasks = [
  {
    name: "test",
    type: "one"
  },
  {
    name: "test2",
    type: 'two'
  }
];
const activities = [
  {
    name: "test",
    type: "one"
  },
  {
    name: "test2",
    type: 'two'
  },
  {
    name: "test3",
    type: "three"
  }
];
 
const knownTypes = new Set();
for (const task of tasks) {
    knownTypes.add(task.type);
}
let tests = activities.filter(a => knownTypes.has(a.type));
console.log(tests);
.as-console-wrapper {
  max-height: 100% !important;
}
const knownTypes = Object.create(null);
for (const task of tasks) {
    knownTypes[task.type] = true;
}
let tests = activities.filter(a => knownTypes[a.type]);
const tasks = [
  {
    name: "test",
    type: "one"
  },
  {
    name: "test2",
    type: 'two'
  }
];
const activities = [
  {
    name: "test",
    type: "one"
  },
  {
    name: "test2",
    type: 'two'
  },
  {
    name: "test3",
    type: "three"
  }
];
 
const knownTypes = Object.create(null);
for (const task of tasks) {
    knownTypes[task.type] = true;
}
let tests = activities.filter(a => knownTypes[a.type]);
console.log(tests);
.as-console-wrapper {
  max-height: 100% !important;
}
Filter array of objects based a nested array of objects

Filter array of objects based a nested array of objects


By : Thejas Babu
Date : March 29 2020, 07:55 AM
will help you You could build new objects and filter historicalData.
This solution does not mutate the original data.
code :
var data = [{ name: "", lastName: "", historicalData: [{ data1: '', data2: 0, }, { data1: '', data2: 30, }] }, { name: "", lastName: "", historicalData: [{ data1: '', data2: 6, }, { data1: '', data2: 1, }] }],
    filtered = data.map(o =>
        Object.assign({}, o, { historicalData: o.historicalData.filter(({ data2 }) => data2 > 2) }));

console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Filter array of objects based on criteria in another array of objects

Filter array of objects based on criteria in another array of objects


By : user2014170
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Use Array.reduce, Array.filter & Array.some
Convert the otherCategories array to an object with title as key and name as value Filter categories array where some subCategory exists with matching values
code :
var categories = [{title:"item1",subCategory:[{title:"subCat1",details:{name:"detail1",email:"test@test.com"}},{title:"subCat2",details:{name:"detail2",email:"test@test.com"}}]},{title:"item2",subCategory:[{title:"subCat1",details:{name:"detail3",email:"test@test.com"}},{title:"subCat2",details:{name:"detail2",email:"test@test.com"}}]}];
var otherCategories = [{title:"subCat1",name:"detail1"}];
var obj = otherCategories.reduce((a,c) => Object.assign(a,{[c.title]:c.name}), {});

categories = categories.filter(v => v.subCategory.some(o => obj[o.title] === o.details.name));
console.log(categories);
Filter array of objects based on content of another array of nested objects

Filter array of objects based on content of another array of nested objects


By : Liz Quilty
Date : March 29 2020, 07:55 AM
I hope this helps . A quick way is to stringify both the people array and check for position in the string.
This saves you the trouble of looping through a nested structure.
code :
var positions = [{ val: 'CEO', label: 'CEO XXX' }, { val: 'CTO', label: 'CTO XXX' }, { val: 'CBO', label: 'CBO XXX' }, { val: 'CLO', label: 'CLO XXX' }]

var people = [{ id: 'AAA', positions: [{ val: 'CEO', label: 'CEO XXX' }] }, { id: 'BBB', positions: [{ val: 'CXO', label: 'CXO XXX' }, { val: 'CEO',
    label: 'CEO XXX' }] }, { id: 'CCC', positions: [{ val: 'CTO', label: 'CTO XXX' }] }];

var stringifiedPeople = JSON.stringify(people)

var newPositions = positions.filter((position) =>
  !stringifiedPeople.includes(JSON.stringify(position))
);

console.log(newPositions)
var positions = [{ val: 'CEO', label: 'CEO XXX' }, { val: 'CTO', label: 'CTO XXX' }, { val: 'CBO', label: 'CBO XXX' }, { val: 'CLO', label: 'CLO XXX' }]

var people = [{ id: 'AAA', positions: [{ val: 'CEO', label: 'CEO XXX' }] }, { id: 'BBB', positions: [{ val: 'CXO', label: 'CXO XXX' }, { val: 'CEO',
    label: 'CEO XXX' }] }, { id: 'CCC', positions: [{ val: 'CTO', label: 'CTO XXX' }] }];

var mappedPositions = {}

people.forEach((p) =>
  p.positions.forEach((position) =>
    mappedPositions[position.val] = true
  )
);

var newPositions = positions.filter((position) => !mappedPositions[position.val]);

console.log(newPositions)
Related Posts Related Posts :
  • get raw text from textarea
  • D3 zoom v3 vs v5
  • How to use NOR gate in JavaScript?
  • Fix Nav Bar after scroll
  • HTML hyperlink not calling JavaScript function
  • List of All Background Images in DOM
  • Using jsAnim.js
  • How to check if XMLHttpRequest's send() supports File
  • Is there a Javascript cron implementation somewhere that I'm missing?
  • Is there any gmap’s api function to concatenate address string from AddressDetails structure?
  • Could not set the selected property JQuery. JQuery Dropdown
  • Jquery making div fadeout with timer
  • Browser EventListenerList Implementation
  • Shopping cart using OO javascript
  • Getting error while running simple javascript using node framework
  • using jquery, How to redirect when drop down list selection changes?
  • Javascript Not Parsing Nested Bbcode
  • run function at ready and keyup event
  • Set field in mongoose document to array length
  • disable Double tap zoom/resize on safari IOS12***
  • how to add a wait in time in a for ..of?
  • Time Spent by user on a web page + Iframe
  • animate.css is not working in Chrome latest version (Version above 73)
  • Row selection and pagination - Vue
  • How can I use function chaining with dates in JavaScript?
  • What is the difference between "delete" and "Reflect.deleteProperty()"
  • How to get attributes of individual elements in jquery array
  • Why do I get different results with "=" vs. "===" in javascript with Conditional (Ternary) Operators
  • I am trying to hold value of document.getElementById("image").src=UserInput +".gif"
  • Array being pushed into another array isn't displaying
  • Is there a React.js NPM module or any other solution for image/object mutli-selection?
  • 80% Javascript Solution for Flags in Codility
  • I want to display background while scrolling down
  • RegEx for matching text between two tags
  • Does having a lot of inner 'helper' functions inside a functional stateless react component will result in worse perform
  • How to submit a form through a button outside the form?
  • ESLint: Use callback in setState when referencing the previous state
  • How to parse state from one component to another in my example?
  • Visible Html select option showing under hidden items
  • Create SVG circle using path with 6 segments
  • Getting error while reading from a text file
  • Read a value from JSON Array without entity
  • Checkbox check or uncheck value null
  • Displaying multiple slider values to users
  • Am doing the destructing right?
  • VueJS data-bind object styling not working
  • Combine array and object destructuring
  • Execution skips promise statements
  • sort an array of objects leaving first field
  • how to highlight table cells in a certain way when hover over
  • Problems when using Chosen Selectors in external helper functions
  • Need to merge two objects together that each have an array to the matching IDs
  • How to get previous 6 months date from current date in javascript
  • how to get object value only without mentioning key from array list using ngFor in angular 7
  • Plugging into on_page_change events in testcafe
  • WithStore: Cannot read property 'state' of undefined (pure-react-carousel)
  • fullcalendar event info in modal popup
  • How do i reduce time complexity of this code
  • Deep comparing object props in React not working as expected
  • JavaScript method to remove case insensitive duplicates from string/Numbers
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk