javascript - 如何更改json数组所有节点的值

标签 javascript json

我有一个具有不同键值的 json 数组,需要使用循环将 ServerUrl 添加到所有节点值的开头,而无需使用 javascript 编写多个语句来完成此操作:

"Urls": [
    { "getCar": "/getAllCars" },
    { "getPerson": "/getAllPersons" },
    { "getBook": "/getAllBooks" }
],
"ServerUrl": "http://192.168.1.1:3000"

预期结果必须是:

"Urls": [
    { "getCar": "http://192.168.1.1:3000/getAllCars" },
    { "getPerson": "http://192.168.1.1:3000/getAllPersons" },
    { "getBook": "http://192.168.1.1:3000/getAllBooks" }
],

如有任何建议,我们将不胜感激。

最佳答案

您可以使用map 将您的对象映射到新对象。这些对象只有一个属性,您可以使用 Object.keys 获取该属性。新对象可以使用计算属性名称功能获得相同的属性名称:

var obj = {
    "Urls": [
        { "getCar": "/getAllCars" },
        { "getPerson": "/getAllPersons" },
        { "getBook": "/getAllBooks" }
    ],
    "ServerUrl": "http://192.168.1.1:3000"
};

var urls = obj.Urls.map(o => Object.keys(o).map(k => ({ [k]: obj.ServerUrl + o[k] }))[0]);

console.log(urls);

关于javascript - 如何更改json数组所有节点的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57210010/

相关文章:

javascript - Angular : one ng-click call the function twice why?

javascript - 更改 Javascript setInterval

java - 更新后未调用 Jquery 事件

javascript - 使用 HOC 加载程序时的重新渲染问题

python - 无法使用请求从 zillow 中抓取自定义属性链接

jquery - 在 jsTree 中,我得到 data.rslt 为未定义

javascript - 更改 div 中跨度的可见性和大小分成两行

javascript - 如何从 javascript 读取包含数组的 json 文件

javascript - 将属性从嵌套模型映射到 extjs 表单 View

javascript - 将数组数组转换为 JSON 对象列表而不是 JSON 字符串