Clément Andraud
Clément Andraud

Reputation: 9269

Create 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 like :

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

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

I'm trying to work in this function :

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

Here I can retrieve my element el.name and el.type. But I don't know how can I create this specific object ? I tried with splice, push... but for create multiple lines etc.. I have no idea.

Upvotes: 3

Views: 215

Answers (2)

Ja9ad335h
Ja9ad335h

Reputation: 5075

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

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

You can use map function itself, but you need to create a new object and add all the fields based on the condition, like this

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' } ]

Upvotes: 3

Related Questions