|
| 1 | +// EXAMPLE 1 - Convert an Array of Objects to an Array of Values in JS |
| 2 | + |
| 3 | +const arrOfObj = [ |
| 4 | + {id: 1, name: 'Alice'}, |
| 5 | + {id: 2, name: 'Bob'}, |
| 6 | +]; |
| 7 | + |
| 8 | +const arr = arrOfObj.map(object => object.name); |
| 9 | +console.log(arr); // 👉️ ['Alice', 'Bob'] |
| 10 | + |
| 11 | +// ------------------------------------------------------------------ |
| 12 | + |
| 13 | +// // EXAMPLE 2 - Dealing with missing properties |
| 14 | + |
| 15 | +// const arr = [ |
| 16 | +// {id: 1, name: 'Alice'}, |
| 17 | +// {id: 2}, |
| 18 | +// {id: 3, name: 'Carl'}, |
| 19 | +// ]; |
| 20 | + |
| 21 | +// const names = arr.map(obj => obj.name); |
| 22 | +// console.log(names); // 👉️ ['Alice', undefined, 'Carl'] |
| 23 | + |
| 24 | +// ------------------------------------------------------------------ |
| 25 | + |
| 26 | +// // EXAMPLE 3 - Removing the undefined values from the array |
| 27 | + |
| 28 | +// const arr = [ |
| 29 | +// {id: 1, name: 'Alice'}, |
| 30 | +// {id: 2}, |
| 31 | +// {id: 3, name: 'Carl'}, |
| 32 | +// ]; |
| 33 | + |
| 34 | +// const names = arr |
| 35 | +// .map(obj => obj.name) |
| 36 | +// .filter(value => { |
| 37 | +// return value !== undefined; |
| 38 | +// }); |
| 39 | +// console.log(names); // 👉️ ['Alice', 'Carl'] |
| 40 | + |
| 41 | +// ------------------------------------------------------------------ |
| 42 | + |
| 43 | +// // EXAMPLE 4 - Convert an Array of Objects to an Array of Values using `forEach()` |
| 44 | + |
| 45 | +// const arrOfObj = [ |
| 46 | +// {id: 1, name: 'Alice'}, |
| 47 | +// {id: 2, name: 'Bob'}, |
| 48 | +// ]; |
| 49 | + |
| 50 | +// const arr = []; |
| 51 | + |
| 52 | +// arrOfObj.forEach(object => { |
| 53 | +// arr.push(object.name); |
| 54 | +// }); |
| 55 | + |
| 56 | +// console.log(arr); // 👉️ ['Alice', 'Bob'] |
| 57 | + |
| 58 | +// ------------------------------------------------------------------ |
| 59 | + |
| 60 | +// // EXAMPLE 5 - Convert an Array of Objects to an Array of Values using `for...of` |
| 61 | + |
| 62 | +// const arrOfObj = [ |
| 63 | +// {id: 1, name: 'Alice'}, |
| 64 | +// {id: 2, name: 'Bob'}, |
| 65 | +// ]; |
| 66 | + |
| 67 | +// const arr = []; |
| 68 | + |
| 69 | +// for (const object of arrOfObj) { |
| 70 | +// arr.push(object.name); |
| 71 | +// } |
| 72 | + |
| 73 | +// console.log(arr); // 👉️ ['Alice', 'Bob'] |
| 74 | + |
| 75 | +// ------------------------------------------------------------------ |
| 76 | + |
| 77 | +// // EXAMPLE 6 - Convert an Array of Objects to an Array of Values using `for` |
| 78 | + |
| 79 | +// const arrayOfObjects = [ |
| 80 | +// {id: 1, name: 'Alice'}, |
| 81 | +// {id: 2, name: 'Bob'}, |
| 82 | +// ]; |
| 83 | + |
| 84 | +// const arr = []; |
| 85 | + |
| 86 | +// for (let index = 0; index < arrayOfObjects.length; index++) { |
| 87 | +// arr.push(arrayOfObjects[index].name); |
| 88 | +// } |
| 89 | + |
| 90 | +// console.log(arr); // 👉️ ['Alice', 'Bob'] |
0 commit comments