Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join() for object properties?

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 />`
}
like image 287
Hedge Avatar asked Aug 10 '17 08:08

Hedge


People also ask

How to join 2 object in JavaScript?

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.

How do you join two objects?

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.

How do you join an array of objects?

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.

How do you merge an array of objects into a single object?

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.


1 Answers

Object.keys could help you:

const printData = Object.keys(data).map(key => `${key}: ${data[key]}`).join("<br />");
like image 153
sp00m Avatar answered Sep 22 '22 01:09

sp00m