请考虑以下对象:
{
"_items": [
{
"_id": "player_1",
"score": {
"a": -4.74,
"b": 0.71,
"c": -4.04,
"d": 3.37,
"e": 0.22,
"f": 1.09,
"g": -2.17
}
}
]
}
我想Map and Reduce并生成一个只包含得分对象的新对象:
{
"a": -4.74,
"b": 0.71,
"c": -4.04,
"d": 3.37,
"e": 0.22,
"f": 1.09,
"g": -2.17
}
我认为这样的事情可能会朝着正确的方向发展,但似乎并没有达到我的期望:
this.service.getscore()
.map(res => res.json())
.map(v => v._items[0].score)
.subscribe(data => { this.sc = data });
console.log(this.sc);
会给我与第一个json相同的结果。
虽然我认识到在服务器端执行此操作可能更好更容易,但在我的情况下这是不可能的。我想知道我在尝试做什么可以在客户端用JavaScript完成。有什么建议?
答案 0 :(得分:0)
越简单越好?:
var json = [{
"_items": [
{
"_id": "player_1",
"score": {
"a": -4.74,
"b": 0.71,
"c": -4.04,
"d": 3.37,
"e": 0.22,
"f": 1.09,
"g": -2.17
}
}
]
}, {
"_items": [
{
"_id": "player_2",
"score": {
"a": -4.74,
"b": 0.71,
"c": -4.04,
"d": 3.37,
"e": 0.22,
"f": 1.09,
"g": -2.17
}
}
]
}];
var scores = [];
for (var i = 0, var j = json.length; i <= j; i++) {
scores.push(json[i]._items[0].score);
}
答案 1 :(得分:0)
您可以尝试下面的代码:
var item = {
"_items": [{
"_id": "player_1",
"score": {
"a": -4.74,
"b": 0.71,
"c": -4.04,
"d": 3.37,
"e": 0.22,
"f": 1.09,
"g": -2.17
}
},
{
"_id": "player_2",
"score": {
"a": -4.74,
"b": 0.71,
"c": -4.04,
"d": 3.37,
"e": 0.22,
"f": 1.09,
"g": -2.17
}
}
]
};
let arrayScores = item._items.map(el => el.score);
console.log(arrayScores);
有arrayScores值:
[{
a: -4.74,
b: 0.71,
c: -4.04,
d: 3.37,
e: 0.22,
f: 1.09,
g: -2.17
}, {
a: -4.74,
b: 0.71,
c: -4.04,
d: 3.37,
e: 0.22,
f: 1.09,
g: -2.17
}]
有意义吗?
答案 2 :(得分:0)
正如Maria Ines Parnisari所提到的,您可以通过插入您收到的JSON来精确提取所需的数据。因此,我们只提取score
的内容并将其分配给对象:
<强>服务强>
getscore() {
return this.http.get('src/data.json')
.map(res => res.json()._items[0].score) // let's get the content of 'score'
}
组件:
ngOnInit() {
this.service.getscore()
.subscribe(data => {
this.sc = data;
})
}
答案 3 :(得分:0)
this.sc = {
"_items": [
{
"_id": "player_1",
"score": {
"a": -4.74,
"b": 0.71,
"c": -4.04,
"d": 3.37,
"e": 0.22,
"f": 1.09,
"g": -2.17
}
}
]
};
console.log(this.sc._items[0].score);
&#13;