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.
-
Sorry, i'm working with symfony, but in this question it's not usefull you are rightClément Andraud– Clément Andraud2015年04月27日 14:51:04 +00:00Commented Apr 27, 2015 at 14:51
-
That's not a valid object ?adeneo– adeneo2015年04月27日 14:52:05 +00:00Commented Apr 27, 2015 at 14:52
-
JSON is a data-format, like XML or CSV.Felix Kling– Felix Kling2015年04月27日 15:21:03 +00:00Commented Apr 27, 2015 at 15:21
2 Answers 2
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' } ]
3 Comments
data: currentObject.name, shouldn't it?data properties, but in theory I suppose this could work, or something ?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 }
});