如何访问对象内部的对象 javascript
2017-10-04
647
我有一个对象初始状态如下:
answersCount: {
Colors: {
Green: 0,
Brown: 0,
Blue: 0,
Red: 0
},
Letters: {
A: 0,
B: 0,
C: 0,
D: 0,
},
Briggs: {
EI: 0,
SN: 0,
TF: 0,
JP: 0
}
},
我有一个 setUserAnswer 函数如下:
setUserAnswer(answer) {
if(answer.trim()) {
const answer_array = answer.split(',');
let updatedAnswersCount = null;
const answersCount = this.state.answersCount;
// copy this.state.answersCount
let answerCountUpdates = update(answersCount, {$merge: {}});
answer_array.forEach((answer) => {
answerCountUpdates = update(answerCountUpdates, {
[answer]: {$apply: (currentValue) => currentValue + 1}
});
}, this);
updatedAnswersCount = update(answersCount, {$merge: answerCountUpdates})
this.setState({
answersCount: updatedAnswersCount,
answer: answer
});
}
}
我正在使用 react-addons-update 使用 $apply 更新值,这个 setUserAnswer 函数将根据用户选择设置答案并将该值增加 +1
问题是,在用户点击 HellYa 按钮后,我想让我的结果看起来像这样:
answersCount: {
Colors: {
Green: 0,
Brown: 1,
Blue: 0,
Red: 0
},
Letters: {
A: 0,
B: 0,
C: 0,
D: 1,
},
Briggs: {
EI: 0,
SN: 0,
TF: 0,
JP: 1
}
},
但是现在它只能输出如下:
answersCount: {
Colors: {
Green: 0,
Brown: 0,
Blue: 0,
Red: 0
},
Brown: null
Letters: {
A: 0,
B: 0,
C: 0,
D: 0,
},
D: null
JP: null
Briggs: {
EI: 0,
SN: 0,
TF: 0,
JP: 0
}
},
如果它有帮助,我有一个用于问题和答案的 quizQuestion.js,例如:
{
question: "I am task oriented in order to achieve certain goals",
answers: [
{
// briggs, color, letter
type: "JP,Brown,D",
content: "Hell Ya!"
},
{
type: " ",
content: "Nah"
}
]
}
1个回答
不妨采用不同的方法,就像这样...
let answersCount = {
colors: {
Green: 0,
Brown: 0,
Blue: 0,
Red: 0
},
letters: {
A: 0,
B: 0,
C: 0,
D: 0,
},
briggs: {
EI: 0,
SN: 0,
TF: 0,
JP: 0
}
};
let applyAnswer = (answer) => {
// example answer = "JP,Brown,D"
let answerArr = answer.split(',');
let briggsAnswer = answerArr[0];
let colorsAnswer = answerArr[1];
let lettersAnswer = answerArr[2];
answersCount['briggs'][briggsAnswer] += 1;
answersCount['colors'][colorsAnswer] += 1;
answersCount['letters'][lettersAnswer] += 1;
return answersCount;
}
那么每次您收到“Hell Ya”时,只需使用答案字符串调用
applyAnswer()
函数,就像这样...
applyAnswer('JP,Brown,D');
更新:我刚刚意识到,由于我们无论如何都在使用 ES6,我们可以通过解构参数来清理这个问题。
let applyAnswer = (answer) => {
// example answer = "JP,Brown,D"
const [ briggsAnswer, colorsAnswer, lettersAnswer ] = answer.split(',');
answersCount['briggs'][briggsAnswer] += 1;
answersCount['colors'][colorsAnswer] += 1;
answersCount['letters'][lettersAnswer] += 1;
return answersCount;
}
Chris Geirman
2017-10-05