reducing array elements using underscore.js - javascript

I am getting an array of data containing many parameters. For example, the data array is in the below format:
var data = [
{
"name":"pradeep",
"age": "32",
"location": "Bangalore"
},
{
"name":"praveen",
"age": "30",
"location": "Mangalore"
},
{
"name":"Ajay",
"age": "32",
"location": "Hubli"
}
]
I want the above array to be reduced to the below format:
[
{
"name":"pradeep"
},
{
"name":"praveen"
},
{
"name":"Ajay"
}
]
How to get this done using Underscore. I tried using the _.pluck but it fetches only the data and not the key.

You could use pure JavaScript to do it, one way is:
data.map(function(obj) {
return {'name': obj.name};
})
If you'd like to parametrize key that should be kept, you may write function like that:
function filterByKey(arr, key) {
return arr.map(function(obj) {
var newObj = {};
newObj[key] = obj[key];
return newObj;
});
}
and use it like that:
var newData = filterByKey(data, 'name');
Cheers

In native JavaScript, you can do it like:
var data = [{
"name": "pradeep",
"age": "32",
"location": "Bangalore"
}, {
"name": "praveen",
"age": "30",
"location": "Mangalore"
}, {
"name": "Ajay",
"age": "32",
"location": "Hubli"
}];
var newData = data.map(function(d) {
return { name: d.name }
});
console.log(newData)

Underscore is not really required, you can do this..
var newData = data.map(function (x) {
return { name: x.name };
});
but if you really want to use underscore this is the way:
var newData = _.map(data, function (x) {
return { name: x.name };
});

For a strictly underscore JS method you can use _.map combined with _.pick:
var newData = _.map(data, function(d) { return _.pick(d, 'name' })
However using _.pick will not be as efficient as just simply returning { name: d.name } in the _.map callback.

You need to use the map function from Undescore. It's a very popular utility from the functional programming and you can also use it natively in the browser.
With Underscore.js the code looks like this:
_.map(data, function(element) {
return {name: element['name']};
})

You can do it using native JavaScript
var result = [];
data.forEach(function(d){
result.push({'name': d.name}) // d is an iterator
})
You could as use map function to return the key value pair
var result = data.map(function(d){
return {'name': d.name}
})

Related

Javascript - Create and populate associative array containing sub arrays

I'm trying to collate some data. I would like to populate an array containing sub arrays, for example, I have some json data that I am iterating over:
{
"name": "name1",
"prices": "209.67"
},
{
"name": "name1",
"prices": "350"
},
{
"name": "name2",
"price": "195.97"
},
I would like to create an array that ends up looking something like the following:
myArray['name1']prices[0] = 209.67,
prices[1] = 350,
['name2']prices[0] = 195.97
I thought that the code below would achieve what I wanted but it doesn't work. It throws an exception. It doesn't seem to recognise the fact that the prices are an array for a given index into the main array. Instead the prices appear at the same level as the names. I want the main array for a given name to contain an inner array of prices.. Does anybody have any idea how I could modify to make this work?
function doStuff() {
var cryptoData = getData();
var datasetValues = {};
datasetValues.names = [];
datasetValues.names.prices = [];
for (var result = 0; result < cryptoData.length; result++) {
var data = cryptoData[result];
if (datasetValues.names.indexOf(data.cryptoname) === -1)
{
datasetValues.names.push(data.cryptoname);
}
// This works
//datasetValues.names.prices.push(data.prices);
// This doesn't!
datasetValues.cryptoNames[data.cryptoname].prices.push(data.prices);
}
}
You could reduce the array by using an object and take a default object if the property is not set. Then push the price.
var data = [{ name: "name1", price: "209.67" }, { name: "name1", price: "350" }, { name: "name2", price: "195.97" }],
result = data.reduce((r, { name, price }) => {
r[name] = r[name] || { name, prices: [] };
r[name].prices.push(+price);
return r;
}, Object.create(null));
console.log(result);
Try this
function parseData(input){
return input.reduce(function(o,i){
o[i.name] = {};
if(!o[i.name]['prices']){
o[i.name]['prices'] = [];
}
o[i.name]['prices'].push(i.prices);
return o;
},{});
}

Lodash merge array with dictionary object key values

I have an array
var keys = ['Name','Id'];
which I want to merge with the dictionary object below
var projects = {
"project1": "11111",
"project2": "22222",
"project3": "33333",
};
to produce the output below
output =
[
{ Name:"project1", Id:"11111"},
{ Name:"project2", Id:"22222"},
{ Name:"project3", Id:"33333"},
]
I have tried using
console.log(_.zipObject(keys, projects));
but this fails woefully
How do I do this using lodash?
Since you have asked to use lodash specifically, you can use _.map.
DEMO
var projects = {
"project1": "11111",
"project2": "22222",
"project3": "33333",
};
var result = _.map(projects, function(value, prop) {
return { Name: prop, id: value };
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
Use Object.keys() with Array.map() to create the array of objects. You can assign the key names by using computed property names:
var keys = ['Name','Id'];
var projects = {
"project1": "11111",
"project2": "22222",
"project3": "33333",
};
var result = Object.keys(projects)
.map(function(k) {
return {
[keys[0]]: k,
[keys[1]]: projects[k]
};
});
console.log(result);

How to turn this ID-based objects into an array of objects?

I have data like this:
{
"-L8BpxbS70KYrZMQUF0W": {
"createdAt": "2018-03-22T16:33:57+08:00",
"email": "ss#ss.ss",
"name": "ss"
},
"-KYrZMQUF0WL8BpxbS70": {
// etc.
}
}
Which I want to turn into this:
[{
id: '-L8BpxbS70KYrZMQUF0W
createdAt: "2018-03-22T16:33:57+08:00",
email: "ss#ss.ss",
name: "ss"
}, {
id: -KYrZMQUF0WL8BpxbS70"
// etc.
}]
I'm started with this:
Object.keys(idBasedObjects).forEach(key => {
console.log(resp[key])
})
But I get undefined.
What's best way of creating this array?
Get the keys and values using Object.entries(), and Array.map() them to to the required form using object spread:
const obj = {"-L8BpxbS70KYrZMQUF0W":{"createdAt":"2018-03-22T16:33:57+08:00","email":"ss#ss.ss","name":"ss"},"-KYrZMQUF0WL8BpxbS70":{}};
const result = Object.entries(obj).map(([id, props]) => ({
id,
...props
}));
console.log(result);
Use Object.keys, Object.assign and map
var output = Object.keys(obj).map( s => Object.assign( obj[s], {id : s} ))
Demo
var obj = {
"-L8BpxbS70KYrZMQUF0W": {
"createdAt": "2018-03-22T16:33:57+08:00",
"email": "ss#ss.ss",
"name": "ss"
},
"-KYrZMQUF0WL8BpxbS70": {
"createdAt": "2018-03-22T16:33:57+08:00",
"email": "s2s#ss.ss",
"name": "ss2"
}
};
var output = Object.keys(obj).map(s => Object.assign(obj[s], {
id: s
}));
console.log(output);

lodash - object transformation

Data Source
var data = {
"2017-08-09": [
{
"time": "09:00",
"available": true
},
{
"time": "13:00",
"available": true
},
{
"time": "13:30",
"available": true
},
]
}
Desired Transformation
newData = [ "2017-08-09": ['09:00','13:00','13:30'] ]
I have tried the following:
function recursiveFunction(collection){
var newData = [];
_.forOwn(collection, function(value, key){
newData.push( {key});
value.map( item => {
if (item.available === true) newData.key = item.time
})
});
console.log(newData)
};
But not quite there :/
http://jsfiddle.net/oa6nbgpy/
Map across the values using mapValues, filter only the available times and pluck the time using map:
var newData = _.mapValues(data, times => _.map(_.filter(times, 'available'), 'time'));
With vanilla JS, use Object#keys to get an array of keys, and convert them to objects using Array#map, Array#filter and computed property names:
var data = {"2017-08-09":[{"time":"09:00","available":true},{"time":"09:30","available":false},{"time":"11:30","available":true}],"2017-08-10":[{"time":"10:00","available":true},{"time":"10:30","available":false}]};
var result = Object.keys(data).map(function(key) {
return {
[key]: data[key]
.filter(function(o) {
return o.available;
})
.map(function(o) {
return o.time;
})
};
});
console.log(result);

Filtering array of Objects Using Lodash or Javascript based on property name

I am Having the Array of objects. Like this
var result=[{"batchId":123, "licenseId":2345ef34, "name":"xxx"},
{"batchId":345, "licenseId":2345sdf334, "name":"www"},
{"batchId":145, "licenseId":234sdf5666, "name":"eee"},
{"batchId":455, "licenseId":asfd236645 },
{"batchId":678, "name":"aaa"}]
i want to have the array which is contains all the three properties. the Output should be like this.
[{"batchId":123, "licenseId":2345ef34, "name":"xxx"},
{"batchId":345, "licenseId":2345sdf334, "name":"www"},
{"batchId":145, "licenseId":234sdf5666, "name":"eee"}]
can anybody Help me on this
This is simple with the array .filter() method:
var result=[
{"batchId":123, "licenseId":"2345ef34", "name":"xxx"},
{"batchId":345, "licenseId":"2345sdf334", "name":"www"},
{"batchId":145, "licenseId":"234sdf5666", "name":"eee"},
{"batchId":455, "licenseId":"asfd236645" },
{"batchId":678, "name":"aaa"}
];
var filtered = result.filter(function(v) {
return "batchId" in v && "licenseId" in v && "name" in v;
});
console.log(filtered);
The function you pass to .filter() is called for each element in the array. Each element for which you return a truthy value will be included in the resulting array.
In the code above I simply test if all three of those specific properties are present, although there are other tests you could use that would get the same result for that data:
var result=[ {"batchId":123, "licenseId":"2345ef34", "name":"xxx"}, {"batchId":345, "licenseId":"2345sdf334", "name":"www"}, {"batchId":145, "licenseId":"234sdf5666", "name":"eee"}, {"batchId":455, "licenseId":"asfd236645" }, {"batchId":678, "name":"aaa"} ];
var filtered = result.filter(function(v) {
return Object.keys(v).length === 3;
});
console.log(filtered);
Note that you need to put your licenseId values in quotes, because they seem to be string values.
var result = [{
"batchId": 123,
"licenseId": '2345ef34',
"name": "xxx"
}, {
"batchId": 345,
"licenseId": '2345sdf334',
"name": "www"
}, {
"batchId": 145,
"licenseId": '234sdf5666',
"name": "eee"
}, {
"batchId": 455,
"licenseId": 'asfd236645'
}, {
"batchId": 678,
"name": "aaa"
}];
function hasProperties(object) {
return object.hasOwnProperty('batchId') && object.hasOwnProperty('licenseId') && object.hasOwnProperty('name')
}
result.filter(e => hasProperties(e));

Categories

Resources