How to remove fields from collection with Lodash? - lodash

var characters = [
{ 'name': 'barney', 'blocked': 'a', 'employer': 'slate' },
{ 'name': 'fred', 'blocked': 'a', 'employer': 'slate' },
{ 'name': 'pebbles', 'blocked': 'a', 'employer': 'na' },
{ 'name': 'pebbles', 'blocked': 'b', 'employer': 'hanna' },
{ 'name': 'wilma', 'blocked': 'c', 'employer': 'barbera' },
{ 'name': 'bam bam', 'blocked': 'c', 'employer': 'barbera' }
];
Using lodash, is there an elegant way to remove specific fields from this collection?

Simply do:
var filteredCollection = _.map(characters, function (c) {
return _.omit(c, ['name']);
});
Now, filteredCollection no longer have the field 'name'.
Here is a jsfiddle.
Note:
If you use NodeJS with Mongoose v4+, you must use: _.omit(c._doc, ['name']);

Related

How to push array to state several times in react native SetState?

I would like to push several arrays to the same state(array) like below.
constructor(props){
super(props);
this.state = {
itemsArray1: [],
itemsArrayMixed: [],
}
}
handleSetState1() {
this.setState({
itemsArray1: [
{name: 'aaa', id: '001', address: 'xxx' },
{name: 'aaa', id: '002', address: 'yyy'},
{name: 'ccc', id: '003', address: 'zzz'},
]
});
this.setState({ itemsArrayMixed: [...itemsArray1] });
}
handleSetState2() {
this.setState({
itemsArray1: [
{name: 'ddd', id: '004', address: 'ttt' },
{name: 'eee', id: '005', address: 'uuu'},
{name: 'fff', id: '006', address: 'www'},
]
});
this.setState({ itemsArrayMixed: [...itemsArray1] });
}
console.log(itemsArrayMixed) // => in itemsArrayMixed, I want to get 6 objects.
Above code is just an example.
In my project, I import 6 arrays that include objects from a different store.
And I want to push all these arrays to the same state (in this case, itemsArrayMixed).
Of course, if I want to handle only one array, that's easy to handle and I know how to do that.
However, I don't know how to push multi arrays to the same state...
You are just adding the new array(itemsArray1) in the mixed array without getting its previous value. you should try this and it will work
handleSetState1() {
let itemArray1 = [
{name: 'aaa', id: '001', address: 'xxx' },
{name: 'aaa', id: '002', address: 'yyy'},
{name: 'ccc', id: '003', address: 'zzz'},
]
this.setState({
itemsArray1
});
this.setState({ itemsArrayMixed: [...this.state.itemsArrayMixed, itemArray1] });
}
This will update the itemArrayMixed and store all value.

lo-dash : JSON parsing and returning required output

I am new to lodash and have below queries. i have attach a sample json of mine. I referred many other post but nothing worked for me
i want to find array with state as true and return below values
name only
name and partno
i also want to just return state and name
[{
'state': true,
'partno': 21,
'idno': 1,
'name': 'abc'
},
{
'state': true,
'partno': 22,
'idno': 2,
'name': 'xyz'
},
{
'state': false,
'partno': 23,
'idno': 3,
'name': 'mnd'
},
{
'state': true,
'partno': 26,
'idno': 4,
'name': 'koi'
},
{
'state': false,
'partno': 21,
'idno': 1,
'name': 'abc'
}
]
The below code does what you need
const data = getData();
console.log('I want to...\n\n');
console.log('1. find array with state as true and return name only')
const result1 = _(data)
.filter('state')
.map('name')
.value();
// logAsJson is a helper function below
logAsJson(result1);
console.log('2. find array with state as true and return name and partno');
const result2 = _(data)
.filter('state')
// pickProperties is a helper function below
.map(pickProperties(['name', 'partno']))
.value();
logAsJson(result2);
console.log('3. just return state and name');
const result3 = _.map(data, pickProperties(['state', 'name']));
logAsJson(result3);
//
// Helper functions
//
function logAsJson(anObject) {
console.log(JSON.stringify(anObject, null, 2));
}
function pickProperties(propsToPick) {
return function mapperFn(anObject) {
return _.pick(anObject, propsToPick);
};
}
function getData() {
return [
{
'state': true,
'partno': 21,
'idno': 1,
'name': 'abc'
},
{
'state': true,
'partno': 22,
'idno': 2,
'name': 'xyz'
},
{
'state': false,
'partno': 23,
'idno': 3,
'name': 'mnd'
},
{
'state': true,
'partno': 26,
'idno': 4,
'name': 'koi'
},
{
'state': false,
'partno': 21,
'idno': 1,
'name': 'abc'
}
];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Maybe I didn't get your question, but here is what you requested:
//Filters your array and creates a new object
yourArray.filter(x => x.state)
.map( x => ({'name':x.name, 'partno':x.partno}))
I didn't know lodash, but taking a look at the documentation, I came with this:
_map(_.filter(yourArray, 'state'), (x) => ({'name':x.name,'partno':x.partno})
Which is pretty much the same. Is there a reason why are you using lodash for this?

How to Filter data using lodash conditionally

How to get the ids as array from this list conditionally.
If the level is one then the user_id otherwise admin_id.
var users = [
{ 'user': 'barney', 'age': 36, 'active': true , level:1, 'user_id':'1', admin_id:'11'},
{ 'user': 'fred', 'age': 40, 'active': false , level:2, 'user_id':'2', admin_id:'22'},
{ 'user': 'barney', 'age': 36, 'active': true , level:1, 'user_id':'3', admin_id:'33'},
{ 'user': 'barney', 'age': 36, 'active': true , level:2, 'user_id':'4', admin_id:'44'},
{ 'user': 'barney', 'age': 36, 'active': true , level:1, 'user_id':'5', admin_id:'55'}
];
Expected array : [1,22,3,44,5]
What you're looking for here is either the native javascript map or lodash's map:
let result1 = users.map(user => user.level === 1 ? user.user_id : user.admin_id);
let result2 = _.map(users, user => user.level === 1 ? user.user_id : user.admin_id);

Nested merging of JSON Objects in Javascript / NodeJS

I have two SQL Queries that return their data as JSON using NodeJS Seriate.
First is categories with two fields, category and name.
categories = [{ category: '1', name: 'category1' },
{ category: '2', name: 'category2' }]
Second one is branches with three fields, category, branch and branchName.
branches = [{ category: '1', branch: '1', name: 'branch1' },
{ category: '1', branch: '2', name: 'branch2' },
{ category: '2', branch: '3', name: 'branch3' },
{ category: '2', branch: '4', name: 'branch4' }]
I want to create one merged JSON, based on the category of each JSON that would have the following structure:
all = [
{ category: '1', name: 'category1',
branches: [
{branch: '1', name: 'branch1' },
{branch: '2', name: 'branch2' }],
{ category: '2', name: 'category2',
branches: [
{branch: '3', name: 'branch3'},
{branch: '4', name: 'branch4'}]
]
I searched and found several methods of joining or extending two json objects but nothing similar to that.
Any help would be appreciated.
This should do it:
categories.forEach(function(c) {
c.branches = branches.filter(function(b) {
var tmp = b.category;
delete b.category;
return tmp === c.category;
});
})

Express configure doesn't work

I use
app.configure( function(){
app.use(express.static(__dirname, '/'));
});
then I figured out it's the old version. Then I used this,
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.use(express.static(__dirname, '/'));
}
but it still give me errors. My whole code is below.
var express = require('express'),
app = express();
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.use(express.static(__dirname, '/'));
}
app.get('/people/:id', function(req, res){`
var customerId = parseInt(req.params.id);
var data = {};
for(var i = 0; i < people.length; i++){
if(people[i].id === customerId){
data = people[i];
break;
}
}
res.json(data);
});
app.get('/people', function(req, res){
res.json(people);
});
app.lisen(8080);
console.log('Listening on express port 8080');
var people = [
{id: 1, name: 'John', city: 'Lisbon', gender: 'male', total: '515.561',
orders: [
{id: 1, product: 'Shoes', total: '100'}
]
},
{id: 2, name:'Abbie', city:'Orlando', gender:'female', total:'3445.34',
orders: [
{id: 2, product: 'Shoes', total: '200.561'}
]
},
{id: 3, name:'Will', city:'Houston', gender:'female', total:'98754.00',
orders: [
{id: 1, product: 'Shoes', total: '300.561'},
{id: 3, product: 'Shoes', total: '330.561'}
]
},
{id: 4, name:'Jim', city:'Paris', gender:'male', total:'15.26',
orders: [
{id: 4, product: 'Shoes', total: '400.561'}
]
},
{id: 5, name:'Bryan', city:'Lisbon', gender:'male', total:'515.561',
orders: [
{id: 5, product: 'Shoes', total: '500.561'}
]
},
{id: 6, name:'Agulera', city:'Orlando', gender:'female', total:'3445.34',
orders: [
{id: 6, product: 'Shoes', total: '600.561'}
]
},
{id: 7, name:'Christeen', city:'Houston', gender:'female', total:'98754.00',
orders: [
{id: 7, product: 'Shoes', total: '700.561'}
]
},
{id: 8, name:'Matt', city:'Paris', gender:'male',total:'15.26',
orders: [
{id: 8, product: 'Shoes', total: '800.561'}
]
}
];
I'm quite new to express and I'm doing this by watching a video. so I want to configure it properly and run it. Please help me with this.
spelling error
app.lisen(8080);
--->
app.listen(8080);
second...
global variables are bad strategy, put the var people as a local variable of app:
http://expressjs.com/api.html#app.locals
app.locals.people = "put the people data here";
Lastly, you should put responses and relevant http error codes to diagnose where there are errors:
for example.....
var yes = "yes";
if ( yes !== data.answer) {
console.log(err);
res.status(401).send(err + "error, you do not have authorized access to this data"); }
else {
console.log("success! You are authorized!")
res.status(200).send(data);
};
Sends back json object data and "ok" status code if condition is met;
status codes:
http://www.w3.org/Protocols/HTTP/HTRESP.html