我的任务是编写一个函数,将元素的值与位于第二个对象内相同位置的值交换为。
{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"}
)发布于 2018-04-09 21:50:27
如果我正确理解了您的问题,就应该这样做(每一步都有一个注释):
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版本。注意,没有发生任何输入对象的变异--您得到两个全新的对象(如果输入对象有嵌套对象作为值,它们可能与输入对象共享某种结构)。
https://stackoverflow.com/questions/49741888
复制相似问题