我有一个解析为JSON对象的字符串。现在,我想检查每个对象键是否包含某个子字符串。在这种情况下,我想将其添加到我的累积对象中。不知何故我一直变得不确定。
这是代码:
const myString = '{ "Address__c": "3QAO", "Id": "OxWQAU", "Address__r": { "Address_Line_1__c": "kjj", "Address_Line_2__c": "kl", "Country__c": "United States", "State__c": "California", "Id": "a022M00001aJIW3QAO", "CountryLabel": "United States", "StateLabel": "California" } }';
const parsed = JSON.parse(myString);
const nameSpace = 'NameSpace__';
const newObj = Object.keys(parsed).reduce((acc,curr) => {
if(curr.includes('__c')){
return {...acc , [nameSpace + curr] : parsed[curr]};
}
},{})
console.log(newObj)
编辑:
所以添加else给我以下结果:
{ NameSpace__Address__c: '3QAO' }
怎么可能只更改一个键。当包含此'__c'字符串的字符串多于1个时
最佳答案
除了添加else { return acc }
之外,还有一个原因是您的结果仅包含一个键。
您的parsed
对象是:
{ Address__c: '3QAO',
Id: 'OxWQAU',
Address__r:
{ Address_Line_1__c: 'kjj',
Address_Line_2__c: 'kl',
Country__c: 'United States',
State__c: 'California',
Id: 'a022M00001aJIW3QAO',
CountryLabel: 'United States',
StateLabel: 'California' } }
所以这意味着
Object.keys(parsed)
是:[ 'Address__c', 'Id', 'Address__r' ]
因此,这些是您可能的
curr
值。从这里开始,如果您也想添加嵌套键,则可以采用递归方法,也可以预先展平结构。
一个不干净的递归解决方案看起来像:
const myString = '{ "Address__c": "3QAO", "Id": "OxWQAU", "Address__r": { "Address_Line_1__c": "kjj", "Address_Line_2__c": "kl", "Country__c": "United States", "State__c": "California", "Id": "a022M00001aJIW3QAO", "CountryLabel": "United States", "StateLabel": "California" } }';
const parsed = JSON.parse(myString);
const nameSpace = 'NameSpace__';
const newObj = parsed => Object.keys(parsed).reduce((acc,curr) => {
if (parsed[curr] instanceof Object) {
return {...acc, ...newObj(parsed[curr])}
}
if(curr.includes('__c')) {
return {...acc , [nameSpace + curr] : parsed[curr]};
} else {
return acc;
}
},{})
console.log("result: ", newObj(parsed))
关于javascript - 减少有条件的不确定的 yield ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57569252/