簡體   English   中英

交換一個Objects值,以及另一個對象的值。 * *的Javascript

[英]Swapping an Objects value, with a value from another object. *Javascript*

我的任務是編寫一個函數,該函數將元素的值與第二個對象內同一位置的值交換。

{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"}
)

如果我正確理解了您的問題,則應該這樣做(每個步驟都用注釋說明):

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版本。 請注意,輸入對象沒有發生變化-您將獲得兩個全新的對象(如果輸入對象具有嵌套對象作為值,則可能與您的輸入對象共享某些結構)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM