0

I try to extract Object from bellow array :

var array = [];
array = 
a,b,c,{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},c,b

imagine extract this :

result = [
{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"}
         ]

I use my code but didn't give me the right answer :

for (var i =0 ; i < array.length ; i++) {
   console.log((array[i].split(','));
} 

In this code I just get each variable in each line I need more thing because in each time maybe I have different array that has for example 2 Object in this example I just have 3 Object.I try to define If I has any Object I can find them and push them in one array.

3
  • 1
    What are a, b and c? Commented Feb 19, 2020 at 14:58
  • they are a variable imagine 1,2,3 Commented Feb 19, 2020 at 15:11
  • I guess my question is could those be arbitrary values? If yes, what makes the objects that you want to extract special? Commented Feb 19, 2020 at 15:12

2 Answers 2

0

You can use Array.filter

var array = [];
array = [
'a','b','c',{"A":"0","f":"1","g":"2"},{"B":"5","v":"8","x":"4"},{"C":"0","f":"1","g":"2"},'c','b'
        ];
        
 let result = array.filter(e => typeof e === 'object');
 console.log(result)

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

4 Comments

Maybe the OP doesn't want the null values.
Maybe? I just added the solution on the provided input as there aren't any null values in the input I will leave as it is. however, filtering out null values isn't a big change.
I use this code but give an error : array.filter is not a function
I create array = [ ] like this but my answer I think doesn't an array this is string I cant use filter for string I should change my question
0

You can use array reduce function. Inside reduce callback check if the type of the element is object then in accumulator array push the element

var array = [];
array = [
  'a', 'b', 'c', {
    "A": "0",
    "f": "1",
    "g": "2"
  }, {
    "B": "5",
    "v": "8",
    "x": "4"
  }, {
    "C": "0",
    "f": "1",
    "g": "2"
  },
  'c', 'b'
];

let newArr = array.reduce((acc, curr) => {

  if (typeof(curr) === 'object') {
    acc.push(curr)
  }
  return acc;
}, []);

console.log(newArr)

1 Comment

Maybe the OP doesn't want the null values

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.