将键/值对添加到数组数组中的对象?
给定以下结构:
const data = {
"show": "Family Guy",
"characters": [
[{name: 'Peter', age: 40, city: 'Quahog'}],
[{name: 'Louis', age: 30}],
[{name: 'Chris', age: 16}],
[{name: 'Stewie', age: 1}]
]
}
我们如何添加每个字符city的密钥/值对:'quahog'
,因此输出看起来如下:
const item = {
"show": "Family Guy",
"characters": [
[{name: 'Peter', age: 40, city: 'Quahog'}],
[{name: 'Louis', age: 30, city: 'Quahog'}], // city added
[{name: 'Chris', age: 16, city: 'Quahog'}], // city added
[{name: 'Stewie', age: 1, city: 'Quahog'}] // city added
]
}
我们尝试使用:
let city = data.characters.[0][0].city;
costs = _.map(items, (itemArray) => {
items = _.map(itemArray, (item) => {
if(!item.city) {
item.city = city;
}
});
但是它不按预期工作,我们可以t获得所需的输出。有什么想法如何实现这一目标?
Given the following structure:
const data = {
"show": "Family Guy",
"characters": [
[{name: 'Peter', age: 40, city: 'Quahog'}],
[{name: 'Louis', age: 30}],
[{name: 'Chris', age: 16}],
[{name: 'Stewie', age: 1}]
]
}
How can we add to each character the key/value pair of city: 'Quahog'
so the output looks as follows:
const item = {
"show": "Family Guy",
"characters": [
[{name: 'Peter', age: 40, city: 'Quahog'}],
[{name: 'Louis', age: 30, city: 'Quahog'}], // city added
[{name: 'Chris', age: 16, city: 'Quahog'}], // city added
[{name: 'Stewie', age: 1, city: 'Quahog'}] // city added
]
}
We tried using:
let city = data.characters.[0][0].city;
costs = _.map(items, (itemArray) => {
items = _.map(itemArray, (item) => {
if(!item.city) {
item.city = city;
}
});
But it's not working as intended and we can't get the desired output. Any idea how to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是用
.duce()
进行操作的另一种方法:当使用
.duce()
而无需第二个参数时,它将选择第一个数组元素作为初始值,然后将其用作模板,以将.city
属性复制到所有其他元素。丢弃.Reduce()
方法的实际返回值,但输入数组本身(data
)在过程中进行了修改,然后在Console中显示.log()
表达式。Here is another way of doing it with
.reduce()
:When using
.reduce()
without a second argument it will pick up the first array element as the initial value which is then used as a template to copy the.city
property to all the other elements. The actual return value of the.reduce()
method is discarded but the input array itself (data
) is modified in the process and is then shown in theconsole.log()
expression.尝试这个
try this one
您可以在没有Lodash的情况下这样做
You can do this without lodash
不确定拥有这些单个项目数组的原因,但是该解决方案将完成工作(我建议您查看创建此数据格式的过程,这有点奇怪)
Not sure about the reason for having these single item arrays but this solution will do the work (I'll recommend you take a look at the process that creates this data format which is a little weird)