0

I have a nested objects in this structure:

myArray = {
  "D": {
    "U": {
      "A300": "B300",
      "A326": "B326",
      "A344": "B344",
      "A345": "B345"
    },
    "P": {
      "A664": "B664",
      "A756": "B756"
    }
  },
  "I": {
    "U": {
      "A300": "B300",
      "A326": "B326"
    },
    "P": {
      "A756": "B756"
    }
  }
};

I am trying to get the data out of it to be only one dimensional (Flatten). I tried the code below but it doesn't work:

var myNewArray = [].concat.apply([], myArray);

and

var myNewArray = myArray.reduce(function(prev, curr) {
  return prev.concat(curr);
});

I want myNewArray to have ["B300","B326","B344","B345","B664","B756"]

11
  • Second answer: stackoverflow.com/questions/10865025/… Commented Nov 21, 2017 at 0:52
  • Already tried that and it gives an error about the reduce function Commented Nov 21, 2017 at 0:54
  • 3
    I think you are working with an object here, not an array Commented Nov 21, 2017 at 0:54
  • @Andy Doesn't work if the elements aren't all in myArray[0][0][0]: jsfiddle.net/barmar/ryfwudqd/2 Commented Nov 21, 2017 at 0:57
  • 1
    @SMH Nope. Just a nested object. Commented Nov 21, 2017 at 1:15

3 Answers 3

2

You can do something like this:

var myArray = [];
myArray[0] = [];
myArray[0][0] = [];
myArray[0][0][0] = [];
myArray[0][0][1] = [];
myArray[0][1] = [];
myArray[0][1][0] = [];

myArray[0][0][0][0] = "abc1";
myArray[0][0][0][1] = "abc2";
myArray[0][0][1][0] = "abc3";
myArray[0][1][0][1] = "abc4";
myArray[0][1][0][1] = "abc5";


function flat(acc, val){
  if(Array.isArray(val)){
     acc = acc.concat(val.reduce(flat, []));
  }else{
   acc.push(val);
  }
  return acc;
}

var newMyArray = myArray.reduce(flat, []);
console.log(newMyArray);

What this does is to recursively reduce all the inner values that are arrays.

It seems that you're dealing with an object. The previous title of your question and the name of the variable are misleading.

In any case, flattening an object is a very similar process.

var myArray = {"D":{"U":{"A300":"B300","A326":"B326","A344":"B344","A345":"B345"},"P":{"A664":"B664","A756":"B756"}},"I":{"U":{"A300":"B300","A326":"B326"},"P":{"A756":"B756"}}};

function flatObj(obj){
   return Object.keys(obj).reduce(function(acc, key){
     if(typeof obj[key] === "object"){
        acc = acc.concat(flatObj(obj[key]));
     }else{
        acc.push(obj[key]);
     }
     return acc;
   }, []);
}


var newMyArray = flatObj(myArray);
console.log(newMyArray);

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

11 Comments

Looks nice, except he's changed the question to an array of objects, not array of arrays.
@SMH I've edited my answer to make to add an example for flattening an object.
@Barmar I've saw that, I've edited my answer to address it.
Might need a unique filter also based on expected results shown. OP needs to clarify
@charlietfl Yes, they seem to be sorted in ascending order.
|
2

I just wanted to add my 2 cents since I was following this question and working on an answer before I left work. I'm home now so I want to post what I came up with.

const obj = {
  x1: { 
    y1: {
      z1: {
          h1: 'abc',
          h2: 'def'
          },
      z2: {
          h1: 123,
          h2: 456
         }
        }
  }
}

const valAll = getPropValuesAll(obj)
console.log(valAll)

function getPropValuesAll(obj, result = []){
  for(let k in obj){
    if(typeof obj[k] !== 'object'){
    	result.push(obj[k])
        continue
    }
    getPropValuesAll(obj[k], result)
  }
  return result
}

Comments

0

It would be easy and safe answer.

var myArray = [["abc1"],[["abc2",,"abc3"]],"abc4",{"r5": "abc5", "r6": "abc6"}];
var myNewArray = [];
function flatten(arr){
  if(Array.isArray(arr)){
    for(var i = 0, l = arr.length; i < l; ++i){
      if(arr[i] !== undefined){
        flatten(arr[i])
      }
    }
  } else if (typeof arr === 'object') {
    for(var key in arr){
      if(arr.hasOwnProperty(key)){
        flatten(arr[key])
      }
    }
  } else {
    myNewArray.push(arr)
  }
}
flatten(myArray)

console.log(myNewArray)

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.