Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to projecting fields of JavaScript object?

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.

like image 559
Ravi Sevta Avatar asked Mar 15 '18 06:03

Ravi Sevta


People also ask

What is projection in JS?

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 .

Which is the correct way to create an object in JavaScript?

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.

How do you print an object in JavaScript?

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.


2 Answers

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;
}
like image 110
ayushgp Avatar answered Sep 21 '22 08:09

ayushgp


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);
like image 37
Hassan Imam Avatar answered Sep 24 '22 08:09

Hassan Imam