使用javascript通过对象动态列表寻求以下结果。定义方法让我获得了不确定的价值指标。
JavaScript代码
var obj = {};
var obj_ = {
"clist_1": "abc",
"clist_2": "def",
"branch_1": "efg"
}
for (let key in obj_) {
if (key.includes("clist_")) {
let num = key.replace(/^\D+/g, '');
obj[num] = obj_.key;
}
}
console.log(obj)
所需结果
{
"1": "abc",
"2": "def"
}
答案 0 :(得分:3)
您可以使用bracket notation。您需要执行obj_[key]
而不是obj_.key
。
var obj = {};
var obj_ = {
"clist_1": "abc",
"clist_2": "def",
"branch_1": "efg"
}
for (let key in obj_) {
if (key.includes("clist_")) {
let num = key.replace(/^\D+/g, '');
obj[num] = obj_[key];
}
}
console.log(obj)
答案 1 :(得分:1)
您需要在密钥的括号中使用property accessor。
obj[num] = obj_[key];
// ^^^^^
然后,您可以使用startsWith
代替includes
来检查字符串的开头部分。
var obj = {};
var obj_ = {
"clist_1": "abc",
"clist_2": "def",
"branch_1": "efg"
}
for (let key in obj_) {
if (key.startsWith("clist_")) {
let num = key.replace(/^\D+/g, '');
obj[num] = obj_[key];
}
}
console.log(obj);
答案 2 :(得分:0)
替代连锁方式:
var obj = {};
var obj_ = {
"clist_1": "abc",
"clist_2": "def",
"branch_1": "efg"
};
Object.keys(obj_)
.map(key=>key.replace(/^\D+/g, ''))
.map(key=>obj[key]=obj_[key]);
console.log(obj);
答案 3 :(得分:0)
您可以这样做:
const obj_ = {"clist_1": "abc","clist_2": "def","branch_1": "efg"};
const obj = Object.keys(obj_)
.filter(k => k.startsWith('clist_'))
.reduce((a, c) => (a[c.match(/\d+/g)] = obj_[c], a), {});
console.log(obj);