A = [{ 123, abc}, { 456, abc}, { 111, def}]
B = [{ 123, xyz}, { 111, def}, { 891, def}]
我在两个阵列A&存储器中存储了谷歌电子表格表的值。 B. 我现在想要创建一个新的数组C,它只包含数组A的行,其中A的第一列与B的第一列匹配。
注意:第一列是唯一ID。在每个阵列的第一列中都没有任何重复。
在给出的示例中,这将导致:
c = [{ 123, abc}, { 111, def}]
这可能吗?
答案 0 :(得分:0)
此代码可以满足您的需求。我测试过了。您可以查看LOGS,并查看结果。 代码从对象数组中创建两个新对象。
var A = [{ 123:"abc"}, { 456:"abc"}, { 111:"def"}];
用于创建:
var newObjA = {123:"abc", 456:"abc", 111:"def"};
对于数组B也是如此。然后代码循环遍历newObjA,并使用newObjA中每个元素的键来查找newObjB中相同值的键。如果匹配,则返回值。如果没有相同值的匹配键,则返回undefined
。
如果返回undefined
,则没有匹配,并且没有数据被放入最终数组。如果匹配,则将newObjA中的匹配元素放入最终数组中。
有很多数据操作可以检索数据并将数据从一种格式移动到另一种格式。你需要研究代码才能搞清楚。
function compareData() {
var A = [{ 123:"abc"}, { 456:"abc"}, { 111:"def"}];
var B = [{ 123:"xyz"}, { 111:"def"}, { 891:"def"}];
Logger.log("A: " + A);
Logger.log("B: " + B);
var arryLengthA = A.length;
var arryLengthB = B.length;
var newObjA = {};
var newObjB = {};
var finalArry = [];
var thisIterationObj = {};
//Convert Array A to an Ojbect A
for (var i = 0; i < arryLengthA; i++) {
Logger.log("count: " + i);
thisIterationObj = {}; //reset to empty
thisIterationObj = A[i];
Logger.log("thisIterationObj: " + thisIterationObj);
for (var thisKey in thisIterationObj) {
Logger.log("thisKey: " + thisKey);
Logger.log(thisIterationObj[thisKey]);
newObjA[thisKey] = thisIterationObj[thisKey];
Logger.log(newObjA[thisKey]);
}
};
//Convert Array B to an Ojbect B
for (var i = 0; i < arryLengthB; i++) {
Logger.log("count: " + i);
thisIterationObj = {}; //reset to empty
thisIterationObj = B[i];
Logger.log("thisIterationObj: " + thisIterationObj);
//Create a new object of all values in array B
for (var thisKey2 in thisIterationObj) {
Logger.log("thisKey2: " + thisKey2);
Logger.log(thisIterationObj[thisKey2]);
newObjB[thisKey2] = thisIterationObj[thisKey2];
Logger.log(newObjB[thisKey2]);
}
};
//Compare Object A to Object B
for (var keyObjA in newObjA) {
thisIterationObj = {};
//Find key of objA in objB
var theMatch = newObjB[keyObjA];
Logger.log("newObjB[keyObjA]: " + newObjB[keyObjA]);
if (theMatch != undefined) {
Logger.log("newObjB[keyObjA] " + newObjB[keyObjA]);
thisIterationObj[keyObjA] = newObjA[keyObjA];
finalArry.push(thisIterationObj);
};
};
//Test the final result by looping through and displaying all values in the final array
Logger.log("finalArry: " + finalArry);
Logger.log("finalArry length: " + finalArry.length);
//This code is a check to test for the correct result
for (var i = 0; i < finalArry.length; i++) {
thisIterationObj = {}; //reset to blank
thisIterationObj = finalArry[i];
for (var finalKey in thisIterationObj)
Logger.log("finalArry value: " + i + ": " + finalKey + " : " + thisIterationObj[finalKey]);
};
};