jsÖÐobjectÊý×éÔõôת»»
¹¤¾ßÊý×é¿ÉÔÚ javascript ÖÐת»»ÎªÆäËûÊý¾Ý½á¹¹£¬°üÀ¨£º×ª»»ÎªÊý×飺ʹÓà map() »ñÈ¡¹¤¾ßÊôÐÔÖµ¡£×ª»»Îª¼üÖµ¶ÔÊý×飺ʹÓà reduce() ½¨É蹤¾ß£¬ÆäÖмüΪ¹¤¾ßµÄÃû³Æ£¬ÖµÎª¹¤¾ßµÄÊôÐÔÖµ¡£×ª»»Îª¹¤¾ß£ºÍ¬ÑùʹÓà reduce() ½¨É蹤¾ß£¬½«ËùÓй¤¾ßÊôÐԺϲ¢Îª¼òµ¥¹¤¾ß¡£×ª»»Îª×Ö·û´®£ºÊ¹Óà json.stringify() ½«¹¤¾ßÊý×éת»»Îª json ×Ö·û´®¡£
ÔõÑù½« JS ÖеŤ¾ßÊý×éת»»ÎªÆäËûÊý¾Ý½á¹¹
ÔÚ JavaScript ÖУ¬¹¤¾ßÊý×éÊÇÒ»ÖÖ³£¼ûµÄÖØ´óÊý¾ÝÀàÐÍ£¬µ«ÓÐʱÎÒÃÇÐèÒª½«Æäת»»ÎªÆäËûÊý¾Ý½á¹¹ÒÔ±ã½øÒ»²½´¦Öóͷ£»ò°´Ìض¨·½·¨ÏÔʾ¡£ÏÂÃæÌṩ¼¸ÖÖÒªÁìÀ´ÊµÏÖ¹¤¾ßÊý×éµÄת»»£º
1. ת»»ÎªÊý×é
Òª½«¹¤¾ßÊý×éת»»ÎªÍ¨ÀýÊý×飬¿ÉÒÔʹÓÃÒÔÏÂÒªÁ죺
const originalObjectArray = [{name: 'John', age: 30}, {name: 'Mary', age: 25}]; const convertedArray = originalObjectArray.map(object => object.name); // ['John', 'Mary']
µÇ¼ºó¸´ÖÆ
2. ת»»Îª¼üÖµ¶ÔÊý×é
ÈôÊÇÐèÒª½«¹¤¾ßÊý×éת»»Îª¼üÖµ¶ÔÊý×飬¿ÉÒÔʹÓà reduce ÒªÁ죺
const convertedArray = originalObjectArray.reduce((acc, object) => { acc[object.name] = object.age; return acc; }, {}); // {'John': 30, 'Mary': 25}
µÇ¼ºó¸´ÖÆ
3. ת»»Îª¹¤¾ß
ÈôÊÇÐèÒª½«¹¤¾ßÊý×éת»»Îª°üÀ¨ËùÓй¤¾ßÊôÐԵļòµ¥¹¤¾ß£¬¿ÉÒÔʹÓà reduce ÒªÁ죺
const convertedObject = originalObjectArray.reduce((acc, object) => { return {...acc, ...object}; }, {}); // {name: 'John', age: 30, name: 'Mary', age: 25}
µÇ¼ºó¸´ÖÆ
4. ת»»Îª×Ö·û´®
Òª½«¹¤¾ßÊý×éת»»Îª×Ö·û´®£¬¿ÉÒÔʹÓà JSON.stringify ÒªÁ죺
const convertedString = JSON.stringify(originalObjectArray); // '[{name:"John",age:30},{name:"Mary",age:25}]'
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÖÐobjectÊý×éÔõôת»»µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡