[英]Array.map function isn't applying to Object value
I'm attempting to re-map an Object that comes from an API call. 我正在尝试重新映射来自API调用的Object。 The format of the response is the following:
响应的格式如下:
data: {
foo: [{
id: "1",
name: "joe",
info: "whatever"
}, {
id: "2",
name: "anna",
info: "whatever"
},...],
bar: [...]
}
The code I'm using to re-map the object inside each response array is: 我用来重新映射每个响应数组中的对象的代码是:
const DATA = response.data;
const entries = Object.entries(DATA);
for (const entry of entries) {
entry[1].map(entry => ({
id: entry["id"],
mixed_info: entry["name"] + ", " + entry["info"]
}));
}
When I console.log the data after this, it shows the same as the initial response, as if it completly ignored the map function. 当我在此之后控制数据时,它显示与初始响应相同的内容,就好像它完全忽略了map函数一样。
What am I doing wrong? 我究竟做错了什么? Thanks for the attention.
感谢您的关注。
map
返回一个新数组,你忽略了调用的结果。
Assign the result of the map
call: 分配
map
调用的结果:
entry[1] = entry[1].map(...);
Array.prototype.map
returns a new array - it doesn't modify the original. Array.prototype.map
返回一个新数组 - 它不会修改原始数组。
You have to reassign the entry
: 您必须重新分配
entry
:
entry[1] = entry[1].map(/*...*/);
However that will only get reflected to the array inside entries
, it won't change DATA
. 但是,这只会反映到
entries
内的数组,它不会改变DATA
。 To change that, you have to either turn the key value pairs back into an object at the end: 要更改它,您必须将键值对转回到最后的对象中:
DATA = Object.fromEntries(entries);
Or you have to reassign the DATA properties while iterating: 或者您必须在迭代时重新分配DATA属性:
DATA[ entry[0] ] = entry[1].map(/*...*/);
I'd do: 我会做:
const { data } = response;
for(const [key, value] of Object.entries(data)) {
data[key] = value.map(/*...*/);
}
let result = {};
for (const entry of entries) {
result[entry[0]] = entry[1].map(entry => ({
id: entry.id,
mixed_info: `${entry["name"] }, ${ entry["info"]}`,
}));
}
'result' contains exact remapped object. 'result'包含精确重映射的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.