Rohit Verma
Rohit Verma

Reputation: 3785

How to convert array object to single array?

I have an object array. 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);

Upvotes: 0

Views: 95

Answers (3)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27202

Are you sure undefined is a string type ? Ideally it should be just undefined and we can filter that out by using Boolean along with filter method.

Live Demo :

const list = [
  { "type": undefined },
  { "type": "test" },
  { "type": "test" }
];
const res = list.map(({ type }) => type).filter(Boolean);

console.log(res);

Upvotes: 1

Wizard
Wizard

Reputation: 503

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)

Upvotes: 1

David
David

Reputation: 218847

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);

Upvotes: 1

Related Questions