Creating an object from another object in JavaScript

I have an object like:

cols : [Object { name="firstname", type="string"}, Object { name="lastname", type="string"}, Object { name="valid", type="checkbox"} ....]

      

I need to create from this object and object, for example:

[
  {
    data: 'firstname'
  },
  {
    data: 'lastname'
  },
  {
    data: 'valid',
    type: checkbox
  }
]

      

The only rule is, if the first object has type = "string", you just need to ignore it (check my second object). And of course this is just an example, so I need an automatic thing.

I am trying to work in this function:

var headers = data.cols.map(function (el, index) {    
    return el.name;
});

      

Here I can get the element el.name

and el.type

. But I don't know how I can create this specific object? I tried with splice

, push

... but for creating multiple lines, etc. I have no idea.

+3


source to share


2 answers


You can use a function map

, but you need to create a new object and add all the fields based on the condition, for example



var data = [{
    name: 'firstname',
    type: 'string'
}, {
    name: 'lastname',
    type: 'string'
}, {
    name: 'valid',
    type: 'checkbox'
}];

var result = data.map(function (currentObject) {

    var object = {
        // Create an object with `name` property
        data: currentObject.name
    };

    if (currentObject.type !== 'string') {
        // create `type` property in the `object`, only if type is not `string`
        object.type = currentObject.type;
    }

    return object;
});

console.log(result);

[ { data: 'firstname' },
  { data: 'lastname' },
  { data: 'valid', type: 'checkbox' } ]

      

+3


source


use map function and return based on condition



var result = data.cols.map(function (d, i) {
    if (d.type == "string") 
        return { data: d.name } 
    else 
        return { data: d.name, type: d.type }
});

      

0


source







All Articles