Home > Mobile >  How to convert array object to single array?
How to convert array object to single array?

Time:11-05

I have object array now i need to convert it single array without key.

I need array like this:-

["test","test"]

I also need to remove that value if I got undefined instead of other value.

My Code:-

const list = [
    {
        "type": "undefined"
    },
    {
        "type": "test"
    },
    {
        "type": "test"
    }
]

var findAndValue = list.map(Object.values);
console.log(findAndValue);

Thanks for your efforts!

CodePudding user response:

If you just want the value from one property, only return that property value from the map operation:

const list = [
  { "type": "undefined" },
  { "type": "test" },
  { "type": "test" }
];
const result = list.map(x => x.type);
console.log(result);

To filter out the "undefined" string, use filter:

const list = [
  { "type": "undefined" },
  { "type": "test" },
  { "type": "test" }
];
const result = list.map(x => x.type).filter(x => x !== "undefined");
console.log(result);

CodePudding user response:

2 steps:

First extract all the values into a list

Second, remove any values you dont want

const values = list.map(({ type }) => type)
cosnt filteredValues = values.filter(val => val !== undefined)
  • Related