1332

Convert array of objects and their properties to array

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?

Answer1:

I suggest to use a fixed array for the keys, because the properties of an object have no order and the order is relevant.

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

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);


Answer2:

_.chain(a) .map(function(x) {return _.values(x)}) .flatten() .filter(function(x) {return x != null;}) .value()

Answer3:

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()

Answer4:

Another underscore solution, similar to the other underscore solutions, but uses <strong>reject</strong> and the <strong>isNull</strong> predicate:

var result = _.chain(data) .map(_.values) .flatten() .reject(_.isNull) .value();

Recommend

  • Oracle/SQL - Finding records with one value excluding nulls
  • How to remove a property from document - mongo / loopback
  • How to select all records from first table and only first matching record from second table?
  • Soap Connection timed out in Java client but not in SOAPUI
  • How to use ResourceDictionary in Windows Phone class library project
  • UIBarButtonItem's action is not called when in a view with a UIGestureRecognizer
  • C++/CLI Thread synchronization including managed and unmanaged code
  • Reading space separated values file in c++ error
  • EntLib Way to Bind “Null” Value to Parameter
  • How can I get the choice “H2” back in the H2 consol?
  • using System.Speech.Synthesis with Windows10 universal app (XAML-C#)
  • How do I shift the decimal place in Python?
  • uml Composition relationships to RDF and OWL
  • Javascript, Regex - I need to grab each section of a string contained in brackets
  • Redshift Querying: error xx000 disk full redshift
  • Django model inheritance, filtering models
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • Install PHP intl extension on MacOS
  • Alternative to overridePendingTransition() - Android
  • Rails Find when some params will be blank
  • $wpdb not working in file of WordPress plugin
  • Django: Count of Group Elements
  • how to adjust image in a panel in Java swing?
  • Deselecting radio buttons while keeping the View Model in synch
  • RectangularRangeIndicator format like triangular using dojo
  • Is possible to count alias result on mysql
  • Possible to stop flickering java tooltip in heavyweight mode?
  • Updated Ionic CLI but shows previous version (Windows)
  • Convert array of 8 bytes to signed long in C++
  • How can I estimate amount of memory left with calling System.gc()?
  • php design question - will a Helper help here?
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • AngularJs get employee from factory
  • Benchmarking RAM performance - UWP and C#
  • JTable with a ScrollPane misbehaving
  • Understanding cpu registers
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • Recursive/Hierarchical Query Using Postgres
  • Running Map reduces the dimensions of the matrices