Получение нулевого значения в массиве - PullRequest
0 голосов
/ 04 февраля 2019

У меня есть файл 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"
}

1 Ответ

0 голосов
/ 04 февраля 2019

Я должен догадаться, но позвольте мне опубликовать его как ответ, чтобы я мог использовать форматирование ...

Учитывая:

const input = {
    "_name":"__tableframe__top",
    "_use-attribute-sets":"common.border__top",
    "__prefix":"xsl"
}

Примечание: значение input.attribute не определено.

    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];
 }

.. поэтому, если этот вход является тем, к которому вы обращаетесь в своем операторе if

input.attribute instanceof Array => false

, он будет истинным, и ваш блок кода будет выполнен, и он говорит:

const example.attribute = [input.attribute]
// example.attribute == [undefined]

Если я вас правильно понимаю, вы можете решить это следующим образом:

$scope.tObj.stylesheet["attribute-set"][4].attribute = (!tableframe__top_content) 
    ? [] 
    : [tableframe__top_content];

Если значение атрибута может быть ложным, вам придется проверить с помощью tableframe__top_content === undefined ||tableframe__top_content === null.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...