我想要执行下面的转换,但我遇到了如何做的麻烦,只是想知道是否有人有任何指针:
//Source
[
{ types: ['a', 'b'] },
{ types: ['b'] },
{ types: ['a', 'c'] }
]
//Transformation
{
'a': [ { types: ['a', 'b'] }, { types: ['a', 'c'] } ],
'b': [ { types: ['a', 'b'] }, { types: ['b'] } ],
'c': [ { types: ['a', 'c'] } ]
}
答案 0 :(得分:1)
var data = [{
types: ['a', 'b']
}, {
types: ['b']
}, {
types: ['a', 'c']
}];
var res = data.reduce(function(a, b) {
b.types.forEach(function(v) { // iterate over inner array
a[v] = a[v] || []; // define the property if not defined
a[v].push(b); // push the object refence
});
return a;
}, {});
document.write('<pre>' + JSON.stringify(res, 0, 3) + '</pre>');
&#13;
答案 1 :(得分:0)
我们可以使用数组&amp;的(function () {
'use strict';
angular
.module('myapp')
.factory('myFactory', ServiceFactory);
myFactory.$inject = ['$http', '$rootScope'];
var config = {
// TO DO : check if anything required
};
/* @ngInject */
function myFactory($http, $rootScope) {
var userName = null;
var userId = null;
var pwd = null;
var service = {
getUserName: getUserName,
setUserName: setUserName,
getPwd:getPwd,
setPwd:setPwd,
};
function getUserName() {
console.log("user name.getUserName." + userName);
return userName;
}
function setUserName(userName) {
console.log("user name.." + userName);
userName = userName;
}
function getPwd() {
console.log("user getPwd.." + pwd);
return pwd;
}
function setPwd(pwd) {
console.log("user setPwd.." + pwd);
pwd = pwd;
}
return service;
}
})();
迭代
.reduce
答案 2 :(得分:0)
var data = [{
types: ['a', 'b']
}, {
types: ['b']
}, {
types: ['a', 'c']
}];
var transform = function(records) {
var obj = {};
records.forEach(function(record){
record.types.forEach(function(value){
obj[value] = obj[value] || []
obj[value].push(record);
});
});
return obj;
};
document.write('<pre>' + JSON.stringify(transform(data)) + '</pre>');
&#13;