通过jQuery中的条件迭代创建一个组合两个现有对象的新数组

时间:2016-02-12 11:34:10

标签: javascript jquery arrays javascript-objects

我有一个主要对象,包含两个主要属性data,其中包含消息,included包含消息的发件人。我想创建一个名为messages的新数组,它将包含两个对象的所有值,但是这个数组中的每个对象都包含数据值,将正确的发送者作为属性添加到每个对象中。< / p>

我能够将主要对象分成两个不同的对象,一个包含数据,另一个包含发件人。

if (jsonAPI.data) {
    $.each(jsonAPI.data, function(index, value) {
        dataObj[index] = value;
    });
}

if (jsonAPI.included) {
    $.each(jsonAPI.included, function(index, value) {
        senders[value.id] = value;
    });
}

我想我必须为dataObj的每个值进行迭代,并检查relationships.sender.data.id是否等于senders.id然后将新属性添加到dataObj,但我不知道怎么写。

我所说的在这个小提琴https://jsfiddle.net/mosmic/f2dzduse/

中可以更清楚

1 个答案:

答案 0 :(得分:1)

工作jsfiddle:https://jsfiddle.net/f2dzduse/5/

var jsonAPI = {<snip>};

var dataObj = {};

if (jsonAPI.data) {
    $.each(jsonAPI.data, function(index, value) {
        dataObj[index] = value;
    });
}

$.each(dataObj, function(index, value) {
    //Prevent error if there is no sender data in included
    if(jsonAPI.included.length - 1 >= index) {
        //check if ids are equal
        if(value.relationships.sender.data.id == jsonAPI.included[index].id) {
            value.sender = jsonAPI.included[index];
        }
    }
});

console.log(dataObj);

此代码假定jsonAPI.data.relationships.sender.data.idjsonAPI.included.id的顺序相同! 如果情况并非总是这样,请告诉我,我将重写代码以循环每个jsonAPI.data,然后循环通过jsonAPI.include以检查相等的ID。这段代码会慢一些,因为它会循环总共jsonAPI.data.length X jsonAPI.include次。

以下是更新后的代码:https://jsfiddle.net/f2dzduse/6/

var jsonAPI = {<snip>};

var dataObj = [];

$.each(jsonAPI.data, function(x, data) {
    dataObj[x] = data;
    $.each(jsonAPI.included, function(y, included) {
        if(data.relationships.sender.data.id == included.id) {
            dataObj[x].sender = included;
        }
    });
});

console.log(dataObj);