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

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

本文关键字:迭代 条件 组合 对象 两个 一个 数组 jQuery 创建      更新时间:2023-09-26

我有一个由两个主要属性组成的主对象,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,但我不知道如何编写它。

我说的话在这个小提琴 https://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);