[英]Convert object into an array Angular
我是javascript和angular的新手。 假設我有一個帶有{"xyz":{Key:info}}
的JSON對象。 我想將{Key:info}
添加到數組中。
我想使“ xyz”成為一個數組。 例如: {"xyz":[{Key:info}]}
這樣,我可以將更多{Key:info}
推入該數組- {"xyz":[{Key:info},{Key:info},{Key:info}]}
。
另外,我每次都需要檢查xyz是否為對象,然后將其設置為數組並僅推送一次。
我不知道如何使用有角度的javascript。
編輯:- 添加了orig JSON
$scope.ContentObj= {
"attribute-set": [
{
"attribute": [
{
"_name": "text-align",
"__prefix": "xsl",
"__text": "end"
},
{
"_name": "end-indent",
"__prefix": "xsl",
"__text": "10pt"
}
],
"_name": "odd__header",
"__prefix": "xsl"
},
{
"attribute": {
"_name": "font-weight",
"__prefix": "xsl",
"__text": "bold"
},
"_name": "pagenum",
"__prefix": "xsl"
}
],
"_version": "2.0",
"__prefix": "xsl"
}
這可能就是您要問的。
if (!angular.isArray($scope.yourObject.xyz)){
$scope.yourObject = {
xyz: []
}
}
$scope.yourObject.xyz.push({Key:'info'})
您可以使用typeof
知道它是否是一個對象,然后可以獲取它的內容並使用它初始化一個數組
let myObject = {"xyz":{Key:"info"}}; if(typeof myObject.xyz === "object"){ //Check if object const content = myObject.xyz; //Get the content myObject.xyz = [content]; //Put the content in an array } console.log(myObject);
如果您需要按照注釋中的要求在代碼中使用它:
if(typeof $scope.ContentObj.stylesheet["attribute-set"][4].xyz === "object"){ //Check if object
const content = $scope.ContentObj.stylesheet["attribute-set"][4].xyz; //Get the content
$scope.ContentObj.stylesheet["attribute-set"][4].xyz = [content]; //Put the content in an array
}
console.log(myObject);
嘗試這種方式。
$scope.yourObject.xyz.push(Object.assign([], yourObject))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.