0

I receive an object and each time it different quantity of strings different every time

Object {
    key_id: 7, 
    key1: "String1, String2", 
    key2: "String1, String2, String3", 
    key3: "String1, String2", 
    key4: "String1, String2";
    …
}

I want to receive

Array = [{key_id: 7, key1: "String1", key1: "String2" ...}]

or

Array = [{key_id: 7, key1: "String1", "String2" ...}]

I need that to make this strings separated to make from them separated links. I am making it on ReactJs with JSX/Babel ES6

3
  • What did you already try? Commented Jun 29, 2017 at 9:51
  • You want one object inside an array, or multiple objects? Commented Jun 29, 2017 at 10:21
  • you can not have multiple same key names in one object. Commented Jun 29, 2017 at 12:12

2 Answers 2

3

Use Object#entries to convert to an array of [key, value] pairs, and Array#map them:

const data = {
  key_id: 7, 
  key1: "String1, String2", 
  key2: "String1, String2, String3", 
  key3: "String1, String2", 
  key4: "String1, String2"
};

const result = Object.entries(data).map(([key, value]) => ({
  [key]: typeof value === 'string' ? value.split(', ') : value
}));

// an array with multiple objects
console.log(result);

// A single object:
console.log(Object.assign({}, ...result));

Note that Object#entries is not part of ES6, and is not supported by IE and Edge.

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

Comments

0

EDIT: Updated the code to change each property to array element.

let data = {
  key_id: 7, 
  key1: "String1, String2", 
  key2: "String1, String2, String3", 
  key3: "String1, String2", 
  key4: "String1, String2"
};

Object.keys(data).forEach(function(key) {
    data[key] = typeof data[key] === 'string' ? data[key].split(', ') : data[key];
});

console.log(data);

Comments

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.