如何修改JS中array.map逻辑实现嵌套对象数组输出?
修改array.map逻辑生成单个对象组成的数组
问题说明
我是编程新手,正在处理现有代码,希望修改array.map的逻辑,使其生成由单个对象组成的数组,而非扁平对象。尝试手动添加{}修改代码,但符号被包含在字符串中,没达到预期效果,求指导。
原代码
const restructuredAttributes = {}; jsonData.attributes.map((attr) => { restructuredAttributes[attr.trait_type] = attr.value; }, []);
当前输出
"attributes":[ "Attribute One":"trait one", "Another attribute":"Another trait", "And another":"And another trait" ]
期望输出
"attributes": [ { "Attribute": "trait", }, { "Another attribute": "Another trait", }, { "And another": "And another trait" } ]
解决方案
原代码的问题在于误用了map:你创建了一个空对象restructuredAttributes,然后用map遍历属性时往这个对象里塞键值对,但map的核心作用是生成新数组,原代码完全没利用它的返回值,反而得到了一个扁平对象。
正确的做法是让map的每个回调返回一个包含单个键值对的对象,这样map会自动把这些对象收集成数组:
写法1:显式返回
const restructuredAttributes = jsonData.attributes.map((attr) => { // 用计算属性名动态设置对象的键 return { [attr.trait_type]: attr.value }; });
写法2:箭头函数隐式返回(更简洁)
const restructuredAttributes = jsonData.attributes.map(attr => ({ [attr.trait_type]: attr.value }));
这里的关键是计算属性名[attr.trait_type]——它能把attr.trait_type的实际值作为对象的属性名,而不是把字符串"attr.trait_type"当作键。之前你手动加{}没成功,大概率是没用到计算属性名,或者没正确返回对象(箭头函数里直接写{}会被当成代码块,需要用()包裹)。
内容的提问来源于stack exchange,提问作者Ripsha
相关产品推荐
相关产品推荐

