[英]How to add / modify a object key-value at a specific position?
I need to add / modify an object value to a specific position. The object will be converted to YAML. That is why the position matters, although it is an object and not an array.我需要将 object 值添加/修改为特定的 position。object 将转换为 YAML。这就是 position 很重要的原因,尽管它是 object 而不是数组。
So the object should have a version
key at the second position:所以 object 应该在第二个 position 处有一个version
密钥:
{
"$schema": "../../../project-schema.json",
"version": "1.2.3", // <- add this or move to this position with modified value
"sourceRoot": "apps/backend/src",
"projectType": "application"
}
Maybe the version is totally missing也许版本完全丢失
{
"$schema": "../../../project-schema.json",
"sourceRoot": "apps/backend/src",
"projectType": "application"
}
or it is at the wrong position或者是错误的position
{
"$schema": "../../../project-schema.json",
"sourceRoot": "apps/backend/src",
"projectType": "application",
"version": "1.2.3"
}
I tried to use a reduce function on the object keys, but this works only if the version
key is missing at all:我尝试在 object 键上使用 reduce function,但这仅在完全缺少version
键的情况下有效:
const insertKey = (key, value, obj, pos) => {
return Object.keys(obj).reduce((ac, a, i) => {
if (i === pos) ac[key] = value
ac[a] = obj[a]
return ac
}, {})
}
insertKey('version', '2.3.4', obj, 1)
let obj = { "$schema": "../../../project-schema.json", "sourceRoot": "apps/backend/src", "version": "1.2.3", // <- add this or move to this position with modified value "projectType": "application" } const insertKey = (key, value, obj, pos) => { return Object.keys(obj).filter(k => k.== key) // just add a filter to remove the key,reduce((ac, a, i) => { if (i === pos) ac[key] = value ac[a] = obj[a] return ac }, {}) } let result = insertKey('version'. '2.3,4', obj. 1) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.