4

from

"data":[{"ja":"大阪市"},{"en":"Osaka"}]

I want to get "ja" and "en".

I tried several ways...

data.map(function(_, i) { return i; });

it returns array of numbers.

console.log(Object.keys(Object.values(data)));

all trials return

(2) [0, 1]
0: 0
1: 1

what can I do ?? please answer me. thank you.

6
  • What is expected output? Commented Apr 9, 2019 at 1:28
  • 1
    @MaheerAli I already said that. I want to ge ["ja", "en"] Commented Apr 9, 2019 at 1:28
  • data.map(x => Object.keys(x)[0]) Bad JSON design though. Would make far more sense if both keys and values just belonged to the same object. Commented Apr 9, 2019 at 1:28
  • @RobbyCornelissen could you recommend? better than [0] ? Commented Apr 9, 2019 at 1:35
  • 1
    The reason for the [0] is that, as I stated, your JSON is badly designed. Commented Apr 9, 2019 at 1:39

2 Answers 2

14

Use map() and return the first key the object. You can get keys using Object.keys()

let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.map(x => Object.keys(x)[0]);
console.log(res)

If you don't want to use [0] use flatMap()

let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.flatMap(x => Object.keys(x));
console.log(res)

Note: The second method will also get the other properties other than first. For example

[{"ja":"大阪市","other":"value"},{"en":"Osaka"}] //["ja","other","en"];
Sign up to request clarification or add additional context in comments.

Comments

4

let data = [{"ja":"大阪市"},{"en":"Osaka"}]
    
let res = data.reduce((arr, o) => {
  return Object.keys(o).reduce((a, k) => {
     if (a.indexOf(k) == -1) a.push(k);
        return a;
     }, arr)
  }, []);
    
console.log(res);

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.