问题
Are there already some javascript functions that do the same as the cakephp functions Set::combine and Set::classicExtract on client side in the browser? http://book.cakephp.org/2.0/en/core-utility-libraries/set.html
So that I can bring this array:
a = [
{
'User' : {
'id' : 2,
'group_id' : 1,
'name' : 'Alfred'
}
},
{
'User' : {
'id' : 12,
'group_id' : 2,
'name' : 'Albert'
}
}
]
with a function like
Set::combine(a, '{n}.User.id', '{n}.User.name')
into the format
a = {
2 : 'Alfred',
12 : 'Albert'
}
for example. But it's not only for this simple example, I'm really looking for a library or something which can do it in a similar way to cakephp. Thanks a lot in advance!
回答1:
No. Javascript has nothing like this built-in.
Either you make these functions yourself, or you use a library such as Underscore.js which provides a lot of utilities like this.
回答2:
I would love to see a JS equivalent to CakePHP's Hash class, but sadly after an hour of Googling, I cannot find anything... Underscore.js and Sugar.js both have some filtering functions, but neither seem to work on multi-dimensional arrays.
In Cake I often do things like this...
Hash::extract($users, '{n}.User.Posts.{n}.Comments.{n}[published=1]');
If anyone knows a JS library that does this, would be very grateful for the tip.
EDIT: I have since found a few options that allow this kind of querying of JSON data (with examples of the syntax they use).
JSPath
.automobiles{.maker === "Honda" && .year > 2009}.modeljson:select() (inspired more by CSS selectors)
.automobiles .maker:val("Honda") .modelJSONPath (inspired more by XPath)
$.automobiles[?(@.maker='Honda')].model
I think JSPath looks the nicest, so I'm going to try and integrate it with my AngularJS + CakePHP app.
回答3:
This is fairly easy in pure javascript:
result = {}
a.forEach(function(item) {
result[item.User.id] = item.User.name;
})
I realize it's only a simple example, but the point is that javascript supports callbacks and first-class functions, and there's simply no need for magic like "{n}.User.name".
来源:https://stackoverflow.com/questions/14004162/cakephp-functions-like-setcombine-in-javascript