[英]Swapping an Objects value, with a value from another object. *Javascript*
My task is to write a function that swaps the value of an element with the value at the same location within the second object. 我的任务是编写一个函数,该函数将元素的值与第二个对象内同一位置的值交换。
{placeOne:10,placeTwo:20},{ten:"firstPlace",twenty:"secondPlace"}
{placeOne:"firstPlace",placeTwo:"secondPlace"},{ten:10,twenty:20} // should equal this
I wanted to try an approach that pushed the objects value into an array, then loop through the object and set each position to the position within the array. 我想尝试一种将对象值推入数组的方法,然后遍历对象并将每个位置设置为数组内的位置。
But I had trouble looping through the object and the array at the same time so I could not solve it that way. 但是我无法同时遍历对象和数组,因此无法以这种方式解决。
Heres what I have so far. 这是我到目前为止所拥有的。
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"}
)
If I understood your problem correctly, this should do it (each step explained with a comment): 如果我正确理解了您的问题,则应该这样做(每个步骤都用注释说明):
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 } ]
You may want to adapt this to your version of JS. 您可能要使其适应您的JS版本。 Note that no mutation of the input objects is taking place -- you get two brand new objects (may share some structure with your input objects if they have nested objects as values).
请注意,输入对象没有发生变化-您将获得两个全新的对象(如果输入对象具有嵌套对象作为值,则可能与您的输入对象共享某些结构)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.