0

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

4
  • 3
    list.map(({ type }) => type).filter(v => v !== "undefined") Commented Nov 4, 2022 at 15:14
  • Does this answer your question? How can I remove a specific item from an array? Commented Nov 4, 2022 at 15:17
  • Are you sure you want to test for undefined given as string value? Commented Nov 4, 2022 at 15:21
  • @RohitVerma Did you get a chance to look into the answer I added ? I hope it will work as per your expectation. Commented Nov 6, 2022 at 16:59

3 Answers 3

1

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

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

Comments

1

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)

Comments

1

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

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.