0

I have a response from my api that returns an object that look like this.

{
    "global.edit": "Edit"
},
{
    "global.add": "Add"
},
{
    "lang.english": "English"
},
{
    "lang.french": "French"
},
{
    "menu.localGroups": "Label's groups"
},
{
    "menu.locals": "Labels"
}

What I am trying to achieve is to convert to a separated comma array.

const MY_NEW_LOCALS_HERE = {
    "global.edit": "Edit",
    "global.add": "Add",
    "lang.english": "English",
    "lang.french": "French",
    "menu.localGroups": "Label's groups",
    "menu.locals": "Labels"
}

So I can add loaded locals to React-Intl.

this.setState({
    localMessage: {
        ...this.state.localMessage,
        MY_NEW_LOCALS_HERE,
    }
})

I spent hours trying to figure it out but I just can't.

Any help on how to achieve this?

If I use OBJECT.join(',') I get an [object Object],[object Object] array.

3
  • Your object is an array, so you need to use the reduce() method. Commented Mar 3, 2020 at 16:13
  • Your object is array and array is object. Commented Mar 3, 2020 at 16:15
  • @Taplar, do you have a quick example? Commented Mar 3, 2020 at 16:19

1 Answer 1

4

You can use deconstruction with the reduce method to put all the keys into a single object.

var temp = [{
    "global.edit": "Edit"
  },
  {
    "global.add": "Add"
  },
  {
    "lang.english": "English"
  },
  {
    "lang.french": "French"
  },
  {
    "menu.localGroups": "Label's groups"
  },
  {
    "menu.locals": "Labels"
  }
];

var result = temp.reduce((r,v)=>({...r, ...v}),{});

console.log(result);

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

3 Comments

Just a question : why are you adding , {} to the end of result ? var result = temp.reduce((r,v)=>({...r, ...v})); works well
@adil.hilmi The last {} is the initial value. array.reduce(closure, initialValue);
Okay it's just an optional argument to put initial value for the result. Thx @Taplar

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.