【问题标题】:Avoid repetition of array push避免重复数组推送
【发布时间】:2019-05-07 22:14:20
【问题描述】:

我创建了一个对象,并在对象内部创建了一个数组,我在其中推送一个来自 json 数据的对象。

$scope.pagenumArr = {"attribute":[],"_name":"pagenum","__prefix":"xsl"};
            if ($scope.pagenumArr.attribute.indexOf($scope.contentObj.stylesheet["attribute-set"][4].attribute) == -1) {
                $scope.pagenumArr.attribute.push($scope.contentObj.stylesheet["attribute-set"][4].attribute);
            }
            console.log($scope.pagenumArr);

scope.contentObj.stylesheet["attribute-set"][4].attribute 是我要推送的数据

{
  "_name": "font-weight",
  "__prefix": "xsl",
  "__text": "bold"
}

我正在用新对象替换旧对象

//replace old pagenum object with new array
            $scope.contentObj.stylesheet["attribute-set"][4] = $scope.pagenumArr;
            console.log($scope.contentObj);

所以当我重新加载我的应用程序时,会在数组"attribute":[] 中创建另一个数组。我只需要数组中的前一个推送对象。如何防止在我的代码中重复推送?我哪里错了?

【问题讨论】:

    标签: arrays angularjs json


    【解决方案1】:

    你可以试试

    if(angular.isUndefined(nameofobject.dataPath[KeyOfData])){
       nameofobject.dataPath = KeyOfData;
    }
    

    【讨论】:

    • 我没有收到这个 nameofobject 。可以根据我的数据给个建议吗?
    • 'pagenumArr',这是一个你用数组名约定给你一个烦人的对象
    • 我怎么能提到KeyOfData?如果我需要按值搜索怎么办?
    • key of data 是你要存储在这个对象中的数据,它看起来像 {Key:info} 其中 key 与 dataPath 相同,Info 是 keyOfData
    • 我认为你没有得到我想要做的事情。我有一个像{attr:{Key:info}} 这样的对象。现在我希望 attr 对象成为一个数组。喜欢{attr:[{Key:info}]}。在此之后我检查对象是否存在于数组中。我想把这个{attr:{Key:info}} --> 替换成这个{attr:[{Key:info}]}。如果attr 是一个对象,则一次。如果找到数组{attr:[{Key:info}]},则跳过。
    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    相关资源
    最近更新 更多