简体   繁体   中英

how to create a complex javascript structure

i want to create a structure like that:

[{title:'Imágenes', extensions:'jpg,gif,png'}, {title:'Todos', extensions:'*'}]

but i need to create it from a string, in this way (in "js+jquery+php rare mode"):

items = 'Imágenes jpg,gif,png|Todos *'.split('|').each(function() {
  list(title, ext) = explode(' ', $this);
  filters[] = array('title' => title, 'ext' => ext);
});

i found structures like:

var theStatus = new Object();
function testIt() {
  theStatus.Home = 'mouseover';
  theStatus['Place'] = 'click';
  for (var i in theStatus)
  {
    alert('theStatus[\''+i+'\'] is ' + theStatus[i])
  }
}

and like:

$.alerts = {
  verticalOffset: -75,
  horizontalOffset: 0,
  repositionOnResize: true,
  overlayOpacity: .01,
  overlayColor: '#FFF'
}

but i cant do nothing functional.

Thanks in advance.

This is how I would do it:

items = 'Imágenes jpg,gif,png|Todos *'.split("|").map(function (itemString) {
    var parts =  itemString.split(" ");
    return { title: parts[0], extensions: parts[1] };
});

Or you can do this if you use jQuery and need to support older browsers:

items = $.map('Imágenes jpg,gif,png|Todos *'.split("|"), function () {
    var parts =  this.split(" ");
    return { title: parts[0], extensions: parts[1] };
});

Your pseudocode is close.

Try the following vanilla javascript:

var str = 'Imágenes jpg,gif,png|Todos *';
var objs = str.split('|');
var objects = [];
for (var i = 0; i < objs.length; i++) {
    var parts = objs[i].split(' ');
    objects.push({ title: parts[0], extensions: parts[1] });
}
// objects is now an array of custom objects in the format you specified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM