How to selecting required properties from object.
Consider following code snippet.Here s contain additional
property,city location that we want to remove.
Solution 1:
Code:
var s = {
name: "sangram",
age: 56,
city:"kankavali",
location: "mumbai",
};
var subset = function ({ name, age }) {
return { name, age };
};
var x = subset(s);
console.log(x);
Output:
{ name: 'sangram', age: 56 }
Explanation:
Here we are passing all properties we want in our derived
object so excluding location & city while pssing remaining
properties name & age.we get a object derived from original
object with only properties that we passed to to function
subset.
Solution 2:
Code:
const foo={
"bar":"sangram",
"baz":"sagar",
"mux":"sachin",
"fch":"swapnil"
}
const { bar,baz, ...qux } = foo
console.log(qux)
Output:
{ mux: 'sachin', fch: 'swapnil' }
Explanation:
Here we are using rest operator as const { bar,baz, ...qux } = foo
we want to omit properties bar & baz so we passed it first then ...qux.
Now qux will get an object derived from foo with all properties except
bar & baz.
No comments:
Post a Comment