0

The following code loops through a JavaScript object and collects only the properties that are arrays:

const building = this.building
let panoramaList = []
for (let key in building) {
  const panoramas = building[key]
  if (Array.isArray(panoramas)) {
    panoramaList.push({ [key]: panoramas })
  }
}
console.log(panoramaList)

In other words, it takes this:

{
  name: '',
  description: ''.
  livingroom: Array[0],
  study: Array[1],
  bedroom: Array[0]
}

and turns it into this:

[
  { livingroom: Array[0] },
  { study: Array[1] },
  { bedroom: Array[0] }
]

However, what I need to produce is this:

{
  livingroom: Array[0],
  study: Array[1],
  bedroom: Array[0]
}

How to accomplish that?

alex
  • 7,111
  • 15
  • 50
  • 77

5 Answers5

1

try this

var output = Object.keys(building).map(function(val){ return { val : building[val] } });

For the final output

var panoramaList = {}
Object.keys(building).forEach(function(val){ 
  if ( Array.isArray(building[val] )
  {
    panoramaList[val] = building[val];
  }
});
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

Change this :

const building = this.building
let panoramaList = []
for (let key in building) {
  const panoramas = building[key]
  if (Array.isArray(panoramas)) {
    panoramaList.push({ [key]: panoramas })
  }
}
console.log(panoramaList)

to this :

const building = this.building
let panoramaList = {}
for (let key in building) {
  const panoramas = building[key]
  if (Array.isArray(panoramas)) {
    panoramaList[key]=panoramas
  }
}
console.log(panoramaList)
trex005
  • 5,015
  • 4
  • 28
  • 41
1

Use Object.keys and try something like this:

var input = {} //...your input array
var keys = Object.keys(input);
var result = {};

keys.forEach(function (key) {
    if (Array.isArray(input[key])) {
        result[key] = input[key];
    }
});
Kamil
  • 424
  • 4
  • 8
0

Make sure to define panoramaList as an object.

This works

var arrays = {
  name: '',
  description: '',
  livingroom: ['1','www'],
  study: ['2','sss'],
  bedroom: ['3','aaa'],
  Kitchen: ['4','bbb'],
}    


const building = arrays
let panoramaList = {};
for (let key in building) {
  const panoramas = building[key]

  if (Array.isArray(panoramas)) {
      panoramaList[key] = panoramas;
  }
}
console.log(panoramaList);

https://jsbin.com/paqebupiva/1/edit?js,console,output

Chad
  • 83
  • 6
0

Rather than building a new object, you might just need to delete the unwanted properties from the object that you have:

var data = {
  name: '',
  description: '',
  livingroom: [],
  study: [1],
  bedroom: [0]
};

Object.keys(data).forEach(function(key) {
  if (!Array.isArray(data[key])) delete data[key];
})

document.write(JSON.stringify(data));
RobG
  • 142,382
  • 31
  • 172
  • 209