-2

I have an object which always have a property and an array. When I print it out with console.log(obj). It likes the following.

 ProjectName: MyTest1
 [0] { foo: 1, bar: 2}
 [1] { foo: 3, bar: 4}
 [2] { foo: 5, bar: 6} 

Or

ProjectName: MyTest2
[0] { foo: 1, bar: 2}
[1] { foo: 3, bar: 4}
[2] { foo: 5, bar: 6} 
[3] { foo: 6, bar: 7}

UPDATE

There are hundreds of them from backend, so the array's size is not fixed. But the object is always a single property plus an array. This object is a combination of a json object and an array. I want a code to extract it. Now I want extract the array from the object and assign it to an array variable so I can loop through it. Which means I must get rid of the first property.

UPDATE1

I want the new object is extracted from the original object by code rather than hard code since we have many dynamic size array.

 [0] { foo: 1, bar: 2}
 [1] { foo: 3, bar: 4}
 [2] { foo: 5, bar: 6}
Hello
  • 796
  • 8
  • 30

2 Answers2

0

Try this?

let superArray: [] = [];

const obj = {
     a: [{ foo: 1, bar: 2}],
     b: [{ foo: 3, bar: 4}],
     c: [{ foo: 5, bar: 6}] 
};

for (var array in obj) {
    superArray = superArray.concat(obj[array]);
}

console.log(superArray);

  • It is not related to my question. I wish you understood the question. – Hello Oct 21 '19 at 00:12
  • are you trying to assign the first property of the object to a variable array? and have only two properties left in the object? – Ibraheem Ghaffar Oct 21 '19 at 00:15
  • Not assign by hard code, see my update., I want to extract it. Because the array could contain 3 elements or more, it is dynamic. – Hello Oct 21 '19 at 00:36
0

see my comment for "already asked"

for short :

var mm=[ 
  { foo: 1, bar: 2} , { foo: 3, bar: 4} ,  { foo: 5, bar: 6} , { foo: 6, bar: 7}
 ];
 mm.property="Hello world";
 console.log("\n1) IsArray ?------------");
 console.log( mm instanceof Array ? "Array":"Other...");
 console.log("2) see mm");
 console.log(mm);

 
 console.log("\nA------- all properties ---------");
 for (var i in mm) {
  if(mm.hasOwnProperty(i)) {
  console.log("property "+i+"=",mm[i]);
  }
 }
 
 
 console.log("\nB------ Array indexes ----------");
 for (var i=0; i<mm.length;i++) {
   console.log("property "+i+"=",mm[i]);
 }
 
 var mm2=JSON.parse(JSON.stringify(mm));
 mm2[9]="index 10???";
 console.log("\nC------ Array indexes ----------");
 for (var i=0; i<mm2.length;i++) {
   console.log("property "+i+"=",mm2[i]);
 }

output :

console output

Advice

Avoid mixing properties and array indexes, use a supplementary property to store your array.

let myDatas={
 datas : [{xx:yy},{zz:ff}],
 title : "xxxx"
};
Community
  • 1
  • 1
Eric
  • 608
  • 4
  • 11
  • Te property is unique. So maybe the best way to do it is to create a dictionary, the key is the property value. Actually the data from the back end is a dictionary. However I have not done the dictionary in typescript yet. – Hello Oct 21 '19 at 22:53