0
配列がオブジェクトの型である場合、次の再帰関数がネストされた配列を出力できないのはなぜですか?オブジェクトの反復処理時にオブジェクトをチェックする場合
期待される出力と実際の出力は、次のとおりです。期待
// dummy encode function
function encode(value) {
return value + " (this value was encoded!)"
}
var arr = {
"title1": {
"item1": "one",
"item2": "two"
},
"title2": "three",
"title3": "four",
"title4": {
"item1": [{
"arrayItem": "First array item"
}, {
"arrayItem": "Second array item"
}]
},
"title5": {
"item1": {
"subItem1": "five",
"subItem2": "six"
}
}
};
function encodeValues(arr) {
var keys = Object.keys(arr);
for (var i = 0; i < keys.length; i++) {
if (!!arr[keys[i]] && typeof arr[keys[i]] === "object") encodeValues(arr[keys[i]]);
else arr[keys[i]] = encode(arr[keys[i]]);
}
return arr;
}
var encodedValues = encodeValues(arr);
console.log(encodedValues)
出力:
{
title1: {
item1: 'one (this value was encoded!)',
item2: 'two (this value was encoded!)'
},
title2: 'three (this value was encoded!)',
title3: 'four (this value was encoded!)',
title4: {
item1: [{
arrayItem: First array item(this value was encoded!)
}, {
arrayItem: Second array item(this value was encoded!)
}]
},
title5: {
item1: {
subItem1: 'five (this value was encoded!)',
subItem2: 'six (this value was encoded!)'
}
}
}
実際の出力:
{
title1: {
item1: 'one (this value was encoded!)',
item2: 'two (this value was encoded!)'
},
title2: 'three (this value was encoded!)',
title3: 'four (this value was encoded!)',
title4: {
item1: [
[Object],
[Object]
]
},
title5: {
item1: {
subItem1: 'five (this value was encoded!)',
subItem2: 'six (this value was encoded!)'
}
}
}
は、ソリューションは、if文で配列のインスタンスに対して次のすなわちチェックの線に沿って何だろうか? :
if (!!arr[keys[i]] && arr[keys[i]] instanceof Array)
encodeValues(arr[keys[i]]);
else if (!!arr[keys[i]] && typeof arr[keys[i]] === "object")
encodeValues(arr[keys[i]]);
else
arr[keys[i]] = encode(arr[keys[i]]);
ありがとう
FIP:出力含む
フルコード(インデントのかなりを固定)。はい、それです。私の権利を置いてくれてありがとう! – fivedoor