【发布时间】:2019-06-28 03:04:41
【问题描述】:
我有一个默认的 JSON 文件:-
{
"_name":"__tableframe__top",
"_use-attribute-sets":"common.border__top",
"__prefix":"xsl"
}
我试图通过创建一个数组来推送一些值,但是在推送数据后我得到了我的数组 undefined 值
{
"_name":"__tableframe__top",
"_use-attribute-sets":"common.border__top",
"__prefix":"xsl",
"attribute":[undefined]
}
首先我检查对象是否包含数组,如果不包含则创建数组。如果已经有一个数组,那么什么也不做。
if(!($scope.tObj.stylesheet["attribute-set"][4].attribute instanceof Array)){
const tableframe__top_content = $scope.tObj.stylesheet["attribute-set"][4].attribute;
$scope.tObj.stylesheet["attribute-set"][4].attribute = [tableframe__top_content];
}
在此之后,我正在检查 _name = something 的属性是否已经存在于数组中。如果没有,则推送。
var checkTableFrameTopColor = obj => obj._name === 'border-before-color';
var checkTableFrameTopWidth = obj => obj._name === 'border-before-width';
var checkTableFrameTopColor_available = $scope.tObj.stylesheet["attribute-set"][4].attribute.some(checkTableFrameTopColor);
var checkTableFrameTopWidth_available = $scope.tObj.stylesheet["attribute-set"][4].attribute.some(checkTableFrameTopWidth);
if( checkTableFrameTopColor_available === false && checkTableFrameTopWidth_available === false ){
$scope.tObj.stylesheet["attribute-set"][4].attribute.push({
"_name": "border-before-color",
"__prefix": "xsl",
"__text": "black"
},{
"_name": "border-before-width",
"__prefix": "xsl",
"__text": "1pt"
}
);
console.log("pushed successfully");
console.log($scope.tObj);
}
我在数组上得到空值和错误TypeError: Cannot read property '_name' of undefined at checkTableFrameTopColor。
我哪里错了?
编辑:-
这样我想实现-
{
"attribute":[
{"_name":"font-weight","__prefix":"xsl","__text":"bold"},
{"_name":"color","__prefix":"xsl","__text":"black"}
],
"_name":"__tableframe__top",
"_use-attribute-sets":"common.border__top",
"__prefix":"xsl"
}
【问题讨论】:
-
刚才有人告诉我使用方括号可能有帮助吗? my question just now
-
到浏览器的开发者工具中查看obj的值
-
尝试使用您的代码创建一个 JSFiddle 并在此处发布链接
-
@zip 否,在上面的代码中,如果
"attribute": { }是一个对象并且存在于主json对象中,那么它将变成数组。但是attribute从一开始就不存在 -
@FakharAhmadRasul 我已经在问题中提到过。获取
{ "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl", "attribute":[undefined] }
标签: javascript arrays angularjs json