I tried several of the map functions but could not find a proper way to get what I want. Here is the case:
Object {Results:Array[3]}
Results:Array[3]
[0-2]
0:Object
id=null
name: "Rick"
upper:"0.67"
1:Object
id="00379321"
name:null
upper:"0.46"
2:Object
id="00323113"
name:null
upper:null
I want my final result to look like this. I wanted all null values to be removed and all the entries tied up like this in an object.
var finalResult = ["Rick","0.67","00379321","0.46","00323113"];
How can I achieve this result?
I suggest to use a fixed array for the keys, because the properties of an object have no order and the order is relevant.
var data = [{ id: null, name: "Rick", upper: "0.67" }, { id: "00379321", name: null, upper: "0.46" }, { id: "00323113", name: null, upper: null }],
result = [];
data.forEach(function (a) {
['id', 'name', 'upper'].forEach(function (k) {
if (a[k] !== null) {
result.push(a[k]);
}
});
});
console.log(result);
_.chain(a)
.map(function(x) {return _.values(x)})
.flatten()
.filter(function(x) {return x != null;})
.value()
Small modification for @andrey's code (requires lodash.js)
var a = [{id:null, name: "Rick", upper:"0.67"}, {id:"00379321", name:null, upper:"0.46"}, {id: "00323113",name:null, upper:null}]
_(a)
.map(function(x) {return _.values(x)})
.flatten()
.without(null)
.value()
Another underscore solution, similar to the other underscore solutions, but uses reject and the isNull predicate:
var result = _.chain(data)
.map(_.values)
.flatten()
.reject(_.isNull)
.value();