我有一个像这样的对象,
{
"Distrubutor":"DISTRIBUTOR1",
"INCLUDE":"INDIA,United States",
"EXCLUDE":"KARNATAKA-INDIA,CHENNAI-TAMILNADU-INDIA",
"PARENT-ID":""
}
我想生成多个对象通过使用Main对象中的INCLUDE属性,任何人都可以帮助我
{
"parent_id":"",
"id":"DISTRIBUTOR1",
"permission":"Granted",
"country_code":"INDIA"
}
2.
{
"parent_id":"",
"id":"DISTRIBUTOR1",
"permission":"Granted",
"country_code":"United States"
}
答案 0 :(得分:1)
您可以拆分包含的国家/地区并映射新对象。
var data = {"Distrubutor":"DISTRIBUTOR1","INCLUDE":"INDIA,United States","EXCLUDE":"KARNATAKA-INDIA,CHENNAI-TAMILNADU-INDIA","PARENT-ID":""},
include = data.INCLUDE.split(',').map(function (a) {
return {
parent_id: "",
id: data.Distrubutor,
permission: "Granted",
country_code: a
};
});
console.log(include);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您可以尝试这样的事情:
output: {
path: path.join(__dirname, 'build'),
publicPath: '/',
filename: 'transformed.js'
},
注意:我已使用Object.assign进行复制,但并非所有浏览器都支持。使用前请参考browser compatibility。您还可以参考以下帖子了解替代方案:What is the most efficient way to deep clone an object in JavaScript?
答案 2 :(得分:0)
这是解决当前问题的另一种方法,也可以回答可能的新问题“你怎么能让它变得更复杂”
class PropertyAdapter {
*populate(target, option){}
}
class DistrubutorAdapter extends PropertyAdapter {
*populate(target, option){
target.id = option;
yield target;
}
}
class ParentIdAdapter extends PropertyAdapter {
*populate(target, option){
target.parent_id = option;
yield target;
}
}
class IncludeAdapter extends PropertyAdapter {
*populate(target, option){
option = option.split(/,/g).map(x=>x.trim()).filter(x=>!!x.length);
for(let v of option){
let obj = Instantinator.copy(target);
obj.country_code = v;
yield obj;
}
}
}
class Instantinator {
static create(){
return {permission: 'Granted'};
}
static copy(src){
return Object.assign({}, src);
}
}
const ADAPTERS = new Map();
class ObjectFactory {
static register(prop, adapter){
ADAPTERS.set(prop, adapter);
}
static create(options){
const pairs = Object.keys(options||{})
.filter(key => ADAPTERS.has(key))
.map(key=> ({value: options[key], adapter: ADAPTERS.get(key)}));
let result = [Instantinator.create()];
for(let pair of pairs){
result = result.reduce((prev, cur) => prev.concat([...pair.adapter.populate(cur, pair.value)]), []);
}
return result;
}
}
ObjectFactory.register('Distrubutor', new DistrubutorAdapter());
ObjectFactory.register('PARENT-ID', new ParentIdAdapter());
ObjectFactory.register('INCLUDE', new IncludeAdapter());
var options = {
"Distrubutor":"DISTRIBUTOR1",
"INCLUDE":"INDIA,United States",
"EXCLUDE":"KARNATAKA-INDIA,CHENNAI-TAMILNADU-INDIA",
"PARENT-ID":""
};
console.log(ObjectFactory.create(options));
.as-console-wrapper { max-height: 100% !important; top: 0; }