【问题标题】:Swapping an Objects value, with a value from another object. *Javascript*用另一个对象的值交换一个对象值。 *Javascript*
【发布时间】:2018-04-09 21:22:46
【问题描述】:

我的任务是编写一个函数,将元素的值与第二个对象中同一位置的值交换。

{placeOne:10,placeTwo:20},{ten:"firstPlace",twenty:"secondPlace"}   

{placeOne:"firstPlace",placeTwo:"secondPlace"},{ten:10,twenty:20} // should equal this

我想尝试一种方法,将对象值推送到数组中,然后循环遍历对象并将每个位置设置为数组中的位置。

但是我在同时循环对象和数组时遇到了麻烦,所以我无法以这种方式解决它。

这是我目前所拥有的。

function swapObj(obj1,obj2){
  let obj1Arr = [];
  let obj2Arr = [];

  for(var i in obj1) {
    obj1Arr.push(obj1[i]);
  }

  for(var k in obj2) {
    obj2Arr.push(obj2[k])
  }

swapObj({placeOne:10,placeTwo:20,placeThree:30,}, 
        {ten:"firstPlace",twenty:"secondPlace",thirty:"thirdPlace"}
)

【问题讨论】:

  • 有什么问题?您不是从数组开始的,那么交换是什么意思?您的代码只是将这 2 个对象放入 swapObj 中的 2 个数组中
  • 对象中键的顺序是任意的,因此您可以创建{ten:10,twenty:20},也可以创建{ten:20,twenty:10}(参见:stackoverflow.com/questions/5525795/…
  • @user3080953 看起来问题不是要在对象内交换键,而是要在数组中交换对象本身,尽管它是模棱两可的。

标签: javascript arrays object for-loop


【解决方案1】:

如果我正确理解了您的问题,应该这样做(每个步骤都有注释):

const swapValues = (a, b) => {
    // obtain arrays of entries ([key, value] pairs) of input objects
    // assuming the entries come in insertion order,
    // which is true in practice for all major JS engines
    const entriesA = Object.entries(a)
    const entriesB = Object.entries(b)

    // output is a pair of objects:
    // first with keys from a, but values from b
    //      at corresponding entry indices
    // second with keys from b, but values from a
    //      at corresponding entry indices
    // assuming both objects have the same number of entries
    //      (might want to check that)
    return entriesA.reduce(
        // for each entry from a with keyA, valueA and index
        (acc, [keyA, valueA], index) => {
            // get corresponding entry from b
            const entryB = entriesB[index]
            // with keyB and valueB
            const [keyB, valueB] = entryB
            // put valueB at keyA in the first output object
            acc[0][keyA] = valueB
            // put valueA at keyB in the second output object
            acc[1][keyB] = valueA

            return acc
        },
        // initially the output objects are empty:
        [{}, {}]
    )
}

console.log(swapValues(
    {placeOne: 10, placeTwo: 20},
    {ten: "a", twenty: "b"}
)) // -> [ { placeOne: 'a', placeTwo: 'b' }, { ten: 10, twenty: 20 } ]

您可能希望根据您的 JS 版本对其进行调整。请注意,输入对象不会发生任何变化——您会得到两个全新的对象(如果输入对象具有嵌套对象作为值,则可能与您的输入对象共享一些结构)。

【讨论】:

  • reduce 中的 [ ] 括号围绕 keyA 和 valueA 做了什么?是把 keyA 和 valueA 放到一个数组中吗?
  • 他们解构[0] reduce 回调的第二个参数。你可以写:(acc, entry, index) => { const keyA = entry[0]; const valueA = entry[1]; /* ... */ } 你会得到同样的结果。 [0] developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
猜你喜欢
  • 2018-04-14
  • 2012-12-05
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
相关资源
最近更新 更多