I have to project some fields of javascript to new object.
for example I have a below object
var obj = { fn : 'Abc',
ln : 'Xyz',
id : 123,
nt : 'Note',
sl : 50000}
and i want new object containing fn and id
var projectedObj = { fn : 'Abc', id : 123 }
on the basis of projection
var projection = { fn : 1, id : 1 }
something like this
var projectedObj = project(obj, projection);
So what is the best way or optimized way to do this.
Overview. Use a projection to control which fields appear in the documents returned by read operations. Many requests only require certain fields, so projections can help you limit unnecessary network bandwidth usage. Projections work in two ways: Explicitly include fields with a value of 1 .
To create an object, use the new keyword with Object() constructor, like this: const person = new Object(); Now, to add properties to this object, we have to do something like this: person.
stringify() method is used to print the JavaScript object. JSON. stringify() Method: The JSON. stringify() method is used to allow to take a JavaScript object or Array and create a JSON string out of it.
Just loop through the projection object and get the keys projected. For example,
function project(obj, projection) {
let projectedObj = {}
for(let key in projection) {
projectedObj[key] = obj[key];
}
return projectedObj;
}
You can use array#reduce
and iterate through all the keys of projection object and based on the key extract the values from the original object and create your new object.
var project = (o, p) => {
return Object.keys(p).reduce((r,k) => {
r[k] = o[k] || '';
return r;
},{});
}
var obj = { fn : 'Abc', ln : 'Xyz', id : 123, nt : 'Note', sl : 50000};
var projection = { fn : 1, id : 1 };
var projectedObj = project(obj, projection);
console.log(projectedObj);
You can also use array#map
with Object#assign
to create your new object.
var project = (o, p) => {
return Object.assign(...Object.keys(p).map(k => ({[k]: o[k]})));
}
var obj = { fn : 'Abc', ln : 'Xyz', id : 123, nt : 'Note', sl : 50000};
var projection = { fn : 1, id : 1 };
var projectedObj = project(obj, projection);
console.log(projectedObj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With