The keys of a and b are all equal
diffObject(a, b) {
let before = [], after = []
Object.keys(a).forEach(key => {
if (a[key] !== b[key]) {
before.push({ ??? }) // 这里应该怎么写,{key: a[key]},但key不能是变量啊
after.push({ ??? })
}
})
return [before, after]
}
Or is there any better, more efficient, more awesome way?
The effect I want to achieve is this
const ob1 = {
name: '辣条',
color: '绿色',
length: 10,
}
const ob2 = {
name: '辣条',
color: '黄色',
length: 12,
}
const diff = diffObject(ob1, ob2)
console.log('diff[0]:', diff[0])
console.log('diff[1]:', diff[1])
// diff[0]: [{color: '绿色'}, {length: 10,}]
// diff[1]: [{color: '黄色'}, {length: 12,}]
The root of this problem is how to use a variable as a key when declaring an object.
ES6 allows literals to be used when defining objects, using
expressions
as property names of objectsAnswer after modifying the question description
If the variable is a string or number
If the variable is an object
Then we need to use ES6 Map
Look at the code. It’s easy to understand. It’s a superset of the previous method
ScreenShot
New writing method
Utilize
reduce
ScreenShot
Before modification
Achieved
Uh-huh. . After reading the problem description for a long time, I’m not quite sure what you want to do
Let’s guess based on the function name and before after. Do you want to put the different attributes and values of object a and object b into before and after respectively? If so, you can take a look at the code below
ScreenShot
Actually your question boils down to
this question:
key will be parsed into a string
"key"
, and the expectation is a variablekey
For example, whenkey="abc",value="123"
the above actually becomes
{"key":"123"}
It should be{"abc":"123"}
The most direct answer is
var o = {}; o[key] = value; ret.push(o);
But is there a simpler way? method?
The following are the results of the discussion
Note: The above answers are listed in chronological order. None of them have been fully tried. Please test carefully before using them. The main thing is to learn the ideas.
As for which solution to choose, I hope to weigh it based on simplicity, performance and readability. Different people have different opinions
This is a summary of a discussion in a QQ group. I am just a porter.
ES6 supports object properties as variables, the writing method is:
In your push parameters, just use this writing method.