0

I have an array of strings, each containing comma separated values.

I'd like to transform this into an array of objects.

For example, I have:

var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
]

... which should end up as:

[
  {
    "field1": "a1",
    "field2": "b1",
    "field3": "c1",
    "field3": "d1"
  },
  {
    "field1": "a2",
    "field2": "b2",
    "field3": "c2",
    "field2": "d2"
  },
  {
    "field1": "a3",
    "field2": "b3",
    "field3": "c3",
    "field3": "d3"
  },
]

I've tried various approaches, like Object.assign and the spread operator. But it seems like there must be a simpler way to do this using destructuring or another approach.

3
  • 3
    Use Array.map(), String.split() and then Array.reduce() on the splitted array. Commented Jun 18, 2020 at 23:25
  • There's nothing in the input that corresponds to the property names. You'll need to write a loop that generates those. Commented Jun 18, 2020 at 23:30
  • you can't do this with destructuring. Destructuring is for turning an object into variables, not for iteration. Commented Jun 18, 2020 at 23:31

2 Answers 2

3

var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
];

const makeProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
  result['field' + (index + 1)] = splitItem;
  return result;
}, {}));

console.log(makeProperties(myarray));

Here is a demo of using words for numbers

var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
];

const numbers = ['one', 'two', 'three', 'four'];

const makeProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
  result[numbers[index]] = splitItem;
  return result;
}, {}));

console.log(makeProperties(myarray));

Sign up to request clarification or add additional context in comments.

6 Comments

This is awesome! As a variation, how would I modify this if I want the fields to have completely different names (e.g., "one", "two", "three", "four")?
use the index to pull from an array ['one', 'two', 'three', 'four']
Great - thanks! That works. Interestingly, though, the fields in each resulting object end up in alphabetical order. Trying to determine now how to maintain their original order.
Object keys stay in order of insertion, it is in the ES6 spec. What do you mean fields end up in alphabetical order? I have added a second snippet to demonstrate this.
Well that's quite odd. When I copy that exact code into jsfiddle.net (where I tested), the result has the keys in alpha order, not order of insertion. See jsfiddle.net/ud3hjs8o.
|
1

You can make double map by mapping the array then their values and replace the default properties by the new one.

var myarray = ["a1,b1,c1,d1", "a2,b2,c2,d2", "a3,b3,c3,d3"];

const fromArrayToObjects = (array) =>
  array.map((value, index) => {
    const o = Object.assign({}, value.split(","));
    Object.keys(o).map((key, i) => {
      Object.defineProperty(
        o,
        "field" + (i + 1),
        Object.getOwnPropertyDescriptor(o, key)
      );
      delete o[key];
    });
    return o;
  });
console.log(fromArrayToObjects(myarray));

4 Comments

This maps to an array of objects with one property, not a single object with multiple properties.
I put the code in a runnable snippet to demonstrate that the output is incorrect.
Oh, it was my mistake, I did not notice that let me fix it.
@AdrianBrand, the solution is fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.