在两个单独的数组中操作数组键值

时间:2017-07-03 00:29:43

标签: javascript arrays

让我们说有两个javascript数组。我想知道的是如何获取第二个数组,并找出是否有另一个人与第一个数组中的某个人拥有相同的favoriteColor。如果有,我希望它切换数组。他们保持与他们转换的人相同的位置。任何人都知道如何做到这一点。

var array1 = [
    {
        name: 'Person 1',
        favoriteNumber: '1',
        hairColor: 'Brown',
        strongHand: 'Left'
    },
    {
        name: 'Person 2',
        favoriteNumber: '2',
        hairColor: 'Brown',
        strongHand: 'Left'
    },
    {
        name: 'Person 3',
        favoriteNumber: '3',
        hairColor: 'Blonde',
        strongHand: 'Right'
    }

var array2 = [
    {
        name: 'Person 4',
        favoriteNumber: '2',
        hairColor: 'Blonde',
        strongHand: 'Right'
    },
    {
        name: 'Person 5',
        favoriteNumber: '22',
        hairColor: 'Blonde',
        strongHand: 'Right'
    }

2 个答案:

答案 0 :(得分:1)

我只是说一个嵌套的for循环。它看起来像这样:

for (let i = 0; i < array1.length; i++) {
    for (let i2 = 0; i2 < array2.length; i2++) {
        if (array1[i].favoriteNumber == array2[i2].favoriteNumber) {
            // swap the two people
            let tmp = array2[i2];
            array2[i2] = array1[i];
            array1[i] = tmp;

            break; // found a match, so skip on to the next i value
        }
    }
}

答案 1 :(得分:0)

显然,我们的想法是在共享相同的收藏号码时将对象分成两个数组。为了实现这一壮举,for循环需要迭代第一个数组中的每个对象。使用嵌套的for循环将每个对象与第二个数组中的对象进行比较是最有效的。如果使用一个很酷的功能来消除必须与临时变量交换,那么交换特别容易:

  

ES6(Firefox和Chrome已经支持它(解构分配数组匹配))

(见discussion。)

&#13;
&#13;
var a = [
  {
    name: "Person 1",
    favoriteNumber: "22",
    hairColor: "Brown",
    strongHand: "Left"
  },
  {
    name: "Person 2",
    favoriteNumber: "2",
    hairColor: "Brown",
    strongHand: "Left"
  },
  {
    name: "Person 3",
    favoriteNumber: "3",
    hairColor: "Blonde",
    strongHand: "Right"
  }
];

var b = [
  {
    name: "Person 4",
    favoriteNumber: "2",
    hairColor: "Blonde",
    strongHand: "Right"
  },
  {
    name: "Person 5",
    favoriteNumber: "22",
    hairColor: "Blonde",
    strongHand: "Right"
  }
];

function switchOnFav() {
  for (let i = 0, max = 3; i < max; i++) {
    for (let j = 0, mx = 2; j < mx; j++) {
      if (a[i]["favoriteNumber"] == b[j]["favoriteNumber"]) {
        [a[i], b[j]] = [b[j], a[i]]; // ECMS 6
      }
    }
  }
}

function showResults(){
  for (let r = 0, m = 3; r < m; r++) {
    console.log( "a[" + r + "]: " + a[r].name);
  }
  for (let s = 0, x = 2; s < x; s++) {
    console.log( "b[" + s + "]: " + b[s].name);
  }
}

d = document;
d.g = d.getElementById;
var sw = d.g("switch");
var res = d.g("show");

sw.addEventListener("click",switchOnFav);
res.addEventListener("click",showResults);
&#13;
button {
background: #00f;
color:#fff;
width:120px;
height:40px;
}
&#13;
<button id="switch">Switch</button>

<button id="show">Show Results</button>
&#13;
&#13;
&#13;