3

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.

3
  • Sorry, i'm working with symfony, but in this question it's not usefull you are right Commented Apr 27, 2015 at 14:51
  • That's not a valid object ? Commented Apr 27, 2015 at 14:52
  • JSON is a data-format, like XML or CSV. Commented Apr 27, 2015 at 15:21

2 Answers 2

3

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' } ]
Sign up to request clarification or add additional context in comments.

3 Comments

It should be data: currentObject.name, shouldn't it?
Note that the initial array is invalid, and the objects within has no data properties, but in theory I suppose this could work, or something ?
@adeneo He can apply this idea, but I had to construct the object on my own. I included that also now :-)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.