提问人:Booba4502 提问时间:10/22/2021 更新时间:10/22/2021 访问量:52
如何创建一个函数,该函数将在 JSON 中更改位于数组内的对象内的属性
How do i create a function that will change the property inside an object that is located inside of an array, in a JSON
问:
所以我目前被困在 JavaScript 作业上几个小时了。
所以我得到了一个包含以下数据的 Json 文件:
{
"owner": "Jun31d",
"info": [{ "id": 1, "name": "bob", "flavour": "vanilla", "age": 43 },
{ "id": 2, "name": "Juneid", "flavour": "Chocolate", "age": 19 },
{ "id": 3, "name": "Patrick", "flavour": "Strawberry", "age": 25 },
{ "id": 4, "name": "Jean", "flavour": "Mint", "age": 31 },
{ "id": 5, "name": "Ahmad", "flavour": "vanilla", "age": 18 },
{ "id": 6, "name": "Ali", "flavour": "Bubblegum", "age": 19 },
{ "id": 7, "name": "Frank", "flavour": "Pistachio", "age": 23 }
]
}
我的教学指示如下:
因此,根据我的理解,我需要创建一个包含两个字符串参数的函数,并且需要将位于数组中的对象内部的属性更改为新属性。
直到现在,这是我所做的:
'use strict'
const iceCream = require('./main.json')
let namespace = {
changeProp : function (newprop,oldprop) {
for (let oldprop in iceCream.info) {
}
}
}
我知道这并不多,但我只是想要一些帮助,以了解我怎样才能在我的同化上再前进一点。
任何帮助都是值得赞赏的,谢谢
答:
0赞
DecPK
10/22/2021
#1
您可以轻松地将 替换为 using map、Object.keys 和 reduceoldKey
newKey
const data = {
owner: "Jun31d",
info: [
{ id: 1, name: "bob", flavour: "vanilla", age: 43 },
{ id: 2, name: "Juneid", flavour: "Chocolate", age: 19 },
{ id: 3, name: "Patrick", flavour: "Strawberry", age: 25 },
{ id: 4, name: "Jean", flavour: "Mint", age: 31 },
{ id: 5, name: "Ahmad", flavour: "vanilla", age: 18 },
{ id: 6, name: "Ali", flavour: "Bubblegum", age: 19 },
{ id: 7, name: "Frank", flavour: "Pistachio", age: 23 },
],
};
function changePropertyName(arr, oldName, newName) {
return arr.map((o) => {
return Object.keys(o).reduce((acc, curr) => {
curr === oldName ? (acc[newName] = o[oldName]) : (acc[curr] = o[curr]);
return acc;
}, {});
});
}
console.log(changePropertyName(data.info, "flavour", "bestFlavour"));
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
0赞
Lakshaya U.
10/22/2021
#2
这是你如何做到的。简单、简单和令人讨厌的解决方案。
const data = {
owner: 'Jun31d',
info: [
{ id: 1, name: 'bob', flavour: 'vanilla', age: 43 },
{ id: 2, name: 'Juneid', flavour: 'Chocolate', age: 19 },
{ id: 3, name: 'Patrick', flavour: 'Strawberry', age: 25 },
{ id: 4, name: 'Jean', flavour: 'Mint', age: 31 },
{ id: 5, name: 'Ahmad', flavour: 'vanilla', age: 18 },
{ id: 6, name: 'Ali', flavour: 'Bubblegum', age: 19 },
{ id: 7, name: 'Frank', flavour: 'Pistachio', age: 23 }
]
};
const renameProperty = (a, e, n) =>
a.map((el) => {
el[n] = el[e];
delete el[e];
return el;
});
console.log(renameProperty(data.info, "id", "_id"));
评论