1

I have below JSON defined in the below manner of set, key and value.

[{
    "set1": {
        "key1": "value1"
    },
    "set2": {
        "key2": "value2"
    },
    "set3": {
        "key3": "value3"
    },
    "set4": {
        "key4": "value4"
    } 
}]

I would like to know how do I use plain/native javascript to get the array of strings in the below manner which consists of only various values.

["value1","value2","value3","value4"]

I have tried using Object.keys and Object.values but still no luck. It would be helpful to know how to handle it in plain javascript and not use any third party libraries.

2
  • Do you want to remove duplicates or only to display all values? Commented May 4, 2021 at 4:36
  • this is just to display all values. Commented May 4, 2021 at 17:04

3 Answers 3

4

A solution:

const data = {
  "set1": {
    "key1": "value1"
  },
  "set2": {
    "key2": "value2"
  },
  "set3": {
    "key3": "value3"
  },
  "set4": {
    "key4": "value4"
  }
}
var result = Object.keys(data).map(_ => Object.values(data[_])[0]);
console.log(result);

This outputs [ 'value1', 'value2', 'value3', 'value4' ]

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

2 Comments

thanks so much, it does work :) but how about if i get the json in a array like [data]
In your example data is an array with a single entry. If that is the general case, you could use data[0]... Otherwise, you could iterate over the items of that array.
2

const data = [{
  "set1": {
    "key1": "value1"
  },
  "set2": {
    "key2": "value2"
  },
  "set3": {
    "key3": "value3"
  },
  "set4": {
    "key4": "value4"
  }
}]

console.log(data.reduce((values, o) => {
  Object.values(o).forEach(v =>
    values.push(...Object.values(v)));
  return values;
}, []));

// Or a more streamined version:

console.log(data.reduce((v, o) => v.concat(
Object.values(o).reduce((v, o) => v.concat(
Object.values(o))
, []))
, []));

Comments

1

This will cover the case with multiple array objects.

let data_array = [
    {
    "set1": {
        "key1": "value1"
    },
    "set2": {
        "key2": "value2"
    },
    "set3": {
        "key3": "value3"
    },
    "set4": {
        "key4": "value4"
    } 
    },
  {
    "set5": {
        "key1": "value5"
    },
    "set6": {
        "key2": "value1"
    },
    "set7": {
        "key3": "value2"
    },
    "set8": {
        "key4": "value3"
    } 
    }
];

let result =  data_array.reduce((accumulator, currentValue)=> {
    accumulator.push(...Object.keys(currentValue).map((key) => Object.values(currentValue[key])[0]));
  return accumulator;
}, []);

console.log(result)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.