在目标C中合并具有相同索引的两个数组

时间:2018-07-06 07:31:06

标签: ios objective-c arrays merge

我想合并两个具有相同索引的数组, 这是我的JSON

var w = 1000;
var h = 1000;

var download = function(){
    html2canvas(document.getElementById("div1"), {
            scale: 2,
        onrendered: function (canvas) {
          var context = canvas.getContext("2d");
          context.scale(2,2);
          context["imageSmoothingEnabled"] = false;
          context["mozImageSmoothingEnabled"] = false
          context["oImageSmoothingEnabled"] = false
          context["webkitImageSmoothingEnabled"] = false
          context["msImageSmoothingEnabled"] = false
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample2.pdf');
            }
        });
    };

我正在使用自定义选择器,现在我希望在同一数组索引中使用“ tier_name”和“ price” “ tier_1:3.9”]。   合并两个数组的代码:

"tier_info": [
    {
        "tier_id": "1",
        "tier_name": "tier-1",
        "price": "3.9",
        "ios_id": "tier-1",
        "android_id": "tier-1"
    },
    {
        "tier_id": "2",
        "tier_name": "tier-2",
        "price": "4.9",
        "ios_id": "tier-2",
        "android_id": "tier-2"
    },
    {
        "tier_id": "3",
        "tier_name": "tier-3",
        "price": "5.9",
        "ios_id": "tier-3",
        "android_id": "tier-3"
    },
    {
        "tier_id": "4",
        "tier_name": "free",
        "price": "0",
        "ios_id": "free",
        "android_id": "free"
    }
]

我知道了

    NSMutableArray *tierTitles = [[NSMutableArray alloc] init];
    tierTitles = [tierArray valueForKey:@"tier_name"];
    NSMutableArray *tierPrice = [[NSMutableArray alloc] init];
    tierPrice = [tierArray valueForKey:@"price"];

    NSMutableArray *combined = [[NSMutableArray alloc] init];
    for (NSUInteger i = 0; i < tierArray.count; i++) {
        [combined addObject: @{tierTitles[i]:tierPrice[i]}];
    }

我想要它:

(
    {
    "tier-1" = "3.9";
},
    {
    "tier-2" = "4.9";
},
    {
    "tier-3" = "5.9";
},
    {
    free = 0;
}
)

我在这里做错什么..任何正确的方法吗?

2 个答案:

答案 0 :(得分:3)

我想问的是您需要一个包含名称和价格作为键值的NSDictionary,您需要枚举每个对象并将其添加到数组中(如果值存在):-

NSMutableArray *results=[NSMutableArray new];
for (NSDictionary *tier in tierArray]) {
    if ([tier[@"tier_name"] length] && [tier[@"price"] length]) {
        [results addObject:@{tier[@"tier_name"]:tier[@"price"]:}];
    }
}

或者像这样创建可变字典:-

NSMutableDictionary *results=[NSMutableDictionary new];
for (NSDictionary *tier in tierArray) {
    if ([tier[@"tier_name"] length] && [tier[@"price"] length]) {
        [results setValue:tier[@"price" forKey:tier[@"tier_name"]];
    }
}

答案 1 :(得分:0)

我认为您应该将字典添加到组合数组中,如下所示

 [tierTitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSMutableDictionary*combinedDict = [[NSMutableDictionary alloc]init];
    [combinedDict setValue:[tierPrice objectAtIndex:idx] forKey:obj];
    [combined addObject: combinedDict];
}];