0

Let's say we have this array

[{name:string,address:string,tel:string},{name:string, address:string, tel:string}]
  • Each objects in the array are of the same type
  • And I want to extract the same attribut trom each object

How can I create this array from the objects contain in the first array ?

[name:string, name:string]

I'm still new to javascript/typescript I'm trying to find an efficient way to do it

any idea ?

An-droid
  • 6,433
  • 9
  • 48
  • 93
  • 1
    What is `{a1,a2,a3}`? This is not an array. Is that a `Set` object? – thefourtheye Jan 23 '18 at 10:02
  • [`Array.prototype.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) – Andreas Jan 23 '18 at 10:03
  • I've simplified the notation, `{a1,a2,a3}` is just a json object where `a1` can be any premitive type. I've seen Map and it seems like doing the same as using forEach or a simple while – An-droid Jan 23 '18 at 10:08
  • Can you post an example object? becuse your curren description is impossible. You cant assign values without keys to object. { a : 1 } = great. {1} = not that much. – Elad Jan 23 '18 at 10:30
  • I editted the example with types but is does not change the problem I think, the objects are simple json objects ^^" – An-droid Jan 23 '18 at 10:37

2 Answers2

2

The elements in the Object do not have any order. But the keys of each value have. So you can access the first key in the object, and use it to get the wanted value.

Like so:

let arrOfObjects = [
     {a: 1, b: 2, c: 3},
     {a: 4, b: 5, c: 6}
];
let newArr = arrOfObjects.map( item => item[Object.keys(item)[0]]); // [1,4]

Or, in your case, if you want only the first name of each person (regardless of order of keys in the object) a better way to do it is like so:

let personArr = [
    {name: "Dan",  address: "here",  phon: "123"},
    {name: "Dany", address: "there", phon: "456"}
];

 let namesArr = arrOfObjects.map( item => item.name);  //  ["Dan", "Dany"]
Elad
  • 2,087
  • 1
  • 16
  • 30
  • outputs [1,4]. What if you want all the values from the object ? Do you not need a loop then? – pixlboy Jan 23 '18 at 11:07
  • You can find the way to do it here: https://stackoverflow.com/questions/7306669/how-to-get-all-properties-values-of-a-javascript-object-without-knowing-the-key#answer-16643074 – Elad Jan 23 '18 at 11:16
0
let m = [];
let a = [{'a1' : 1 ,'a2': 2, 'a3': 3},{'b1': A, 'b2': B, 'b3': C}];
let arrLength = a.length;
let objLength = 3;

for(let i = 0; i < objLength; i++){
    for(let j = 0; j < arrLength; j++){
        m.push(a[j][Object.keys(a[j])[i]]);
    }
}

OUTPUT

[1, "A", 2, "B", 3, "C"]

pixlboy
  • 1,452
  • 13
  • 30