简体   繁体   中英

Filter Single JSON by Key Name

I want to create some type of Laravel's only method in JS.

I have the following JSON:

let obj = {
             name: "Wil",
             age: "20",
             id: "1"
          }

And a filters array:

let filters = ['name', 'age'];

In this case i want a function that takes 2 parameters:

const filterJSON = (object, filters) => {

}

And i want the function to return the same object with ONLY the key names i pass in the filters array.

In this case:

{
   name: "Wil",
   age: "20"
}

I have a while trying with .map and .filter but i'm not getting what i want, the examples i found are only with array of objects, but in this case i need to filter a single object.

Thank you.

Can use a simple reduce() to return a new object

 let obj = { name: "Wil",age: "20",id: "1"} let filters = ['name', 'age']; const filterJSON = (obj, fil) => fil.reduce((a,c) => (a[c] = obj[c], a),{}) console.log(filterJSON(obj, filters)) 

Use Object.keys and reduce

 const obj = { name: "Wil", age: "20", id: "1" } let filters = ['name', 'age']; const filterJSON = (object, filters) => Object.keys(object).reduce((a, v) => { if (filters.some(f => f === v)) { a[v] = object[v]; } return a; }, {}); console.log(filterJSON(obj, filters)); 

Create a new object, then loop through the array and add key and value using square bracket notation from the object

 let obj = { name: "Wil", age: "20", id: "1" } let filters = ['name', 'age']; function getObj(arr, obj) { let newObj = {}; filters.forEach(function(elem) { newObj[elem] = obj[elem] }) return newObj; }; console.log(getObj(filters, obj)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM