I am joining object properties by using a for..in
loop. I wonder if there is an even easier way to this like join()
for Arrays.
const data = { a: '213', b: 'asv', c: 'sdfs' }
let printData = ''
for (let attr in data) {
printData += `${attr}: ${data[attr]}<br />`
}
To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.
If you want to merge the second object into the first object, instead of creating a new object, you can use Object. assign() . The Object. assign(target, source) function merges the source into the target.
Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.
Object.keys
could help you:
const printData = Object.keys(data).map(key => `${key}: ${data[key]}`).join("<br />");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With