我是AngularJS的初学者,现在我正在构建一个简单的应用程序。
我有一些像这样的HTML代码
<table class="table" ng-repeat="(attr, assets) in customize.product.attributes">
<tr>
<th colspan="2">{{attr}}</th>
</tr>
<tr ng-repeat="asset in assets">
<td>
{{asset}}
</td>
<td>
<file-uploader class="form-control"
image-width="{{galleryConfigs.width}}"
image-height="{{galleryConfigs.height}}"
image-crop-width="{{galleryConfigs.width}}"
image-crop-height="{{galleryConfigs.height}}"
max-size="5000"
allowed-extensions="png,jpeg,jpg"
result-model="customize.assets[attr][asset]">
</file-uploader>
</td>
</tr>
</table>
这是我的代码JS
$scope.create = function(published){
var published = published || false,
customize = angular.copy($scope.customize);
if(published)
customize.published = true;
dataProvider.Customize.save(customize).$promise
.then(function(_customize){
if(!_customize) throw 'Error System';
toast.create({content:'Succes', className:'success'});
$state.go('pos.product.customize.show',{customizeId:_customize.id});
}).catch(function (error){
$log.error(error);
});
};
当我推送数据时,如下所示存储如下所示的数据
"assets" : {
"part 1" : {
"black" : [
"/file/c36a3297-11bb-4028-8cb7-d750b98436ec.png",
"/file/4a6ec1ed-c3b1-48f9-84c0-61dd0f6da08a.png",
"/file/c66ac97a-18be-4e79-9ec1-ca67ab37d3f3.png"
],
"red" : [
"/file/c36a3297-11bb-4028-8cb7-d750b98145ec.png",
"/file/4a6ec1ed-c3b1-48f9-8cb7-61dd0f6da07a.png",
"/file/c66ac97a-18be-4e79-8cb7-ca67ab37d3c3.png"
]
}
}
即使我想用如下所示的结构保存数据
"assets" : {
"part 1" : {
"black" :"/file/a11c553f-de74-48e2-93a0-6fc72a54fa9b.png",
"red" :"/file/a11c553f-de74-48e2-93a0-6fc72a54ga8c.png"
}
}
有什么办法吗?
答案 0 :(得分:2)
假设资产可以包含许多部分,这里的解决方案将返回每个颜色数组中的第一个项目:
var result = _.mapObject(assets, function(asset){
return _.mapObject(asset, _.first);
});
类似于我昨天提出的问题How to change data array to be object using javascript?
的答案
var assets = {
"part 1" : {
"black" : [
"/file/c36a3297-11bb-4028-8cb7-d750b98436ec.png",
"/file/4a6ec1ed-c3b1-48f9-84c0-61dd0f6da08a.png",
"/file/c66ac97a-18be-4e79-9ec1-ca67ab37d3f3.png"
],
"red" : [
"/file/c36a3297-11bb-4028-8cb7-d750b98145ec.png",
"/file/4a6ec1ed-c3b1-48f9-8cb7-61dd0f6da07a.png",
"/file/c66ac97a-18be-4e79-8cb7-ca67ab37d3c3.png"
]
}
}
var result = _.mapObject(assets, function(asset){
return _.mapObject(asset, _.first);
});
document.getElementById('results').textContent = JSON.stringify(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>
<pre id="results"></pre>
&#13;
答案 1 :(得分:0)
这是一个可以从数组中创建对象的函数:
['apple', 'orange', 'grapes']
此功能可将{1: 'apple', 2: 'orange', 3: 'grapes'}
数组转换为function arrayToObjWithOneProperty(a) {
//Create an empty object
var obj = {value: ''};
//Go through the array and add elements as properties to the object
a.forEach(function(element){
obj.value = obj.value + element + ',';
})
return obj;
}
如果您需要一个具有单个属性的对象,该对象包含数组的所有元素作为字符串,请按以下步骤操作:
['apple', 'orange', 'grapes']
此功能会将{value: 'apple,orange,grapes'}
转换为componentWillUnmount