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

Creating a new array combining two existing objects through iteration with condition in jQuery

我有一个包含两个主要属性的主对象,data 包含消息,included 包含消息的发送者。我想创建一个名为 messages 的新数组,它将包含两个对象的所有值,但在某种程度上,该数组中的每个对象都将包含数据值,并将正确的发件人添加为 属性其中

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

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,但是我不知道怎么写。

这个我说的可以更清楚fiddlehttps://jsfiddle.net/mosmic/f2dzduse/

工作 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);