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.

2 Answers2

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)
AZ_
  • 3,094
  • 1
  • 9
  • 19
  • Maybe the OP doesn't want the `null` values. – Ele Feb 19 '20 at 15:03
  • `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. – AZ_ Feb 19 '20 at 15:05
  • I use this code but give an error : array.filter is not a function – faezanehhabib Feb 19 '20 at 15:10
  • 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 – faezanehhabib Feb 19 '20 at 15:15
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)
brk
  • 48,835
  • 10
  • 56
  • 78