Bille
Bille

Reputation: 401

How do you extract a property from a nested object in Typescipt?

I have to create an array containing all 'value' properties from an array of nested objects.

I have tried with array.map(), but cant find a way to make it fit my use-case, because the objects are named dynamically.

Data example:

{
    "array": [{
        "BEH": {
            "value": 2,
            "count": 4
        },
        "FHT": {
            "value": 4,
            "count": 1
        }
    }]
}

Expected result: [2,4] Or even better: [{BEH: 2, FHT: 4}]

Upvotes: 0

Views: 1414

Answers (4)

Saurabh Yadav
Saurabh Yadav

Reputation: 3386

You can simply use for loop to iterate over loop and for in loop to iterate over object

var array = [{
        "BEH": {
            "value": 2,
            "count": 4
        },
        "FHT": {
            "value": 4,
            "count": 1
        }
 }];

    var result = [];
    for(let i = 0; i < array.length; i++) {
        let item = array[i];
        let obj = {};
        for(let j in item) {
            if(item.hasOwnProperty(j)) {
                obj[j] = item[j]['value'];
            }
        }
        result.push(obj);
    }

    console.log(result);

Upvotes: 0

Hải B&#249;i
Hải B&#249;i

Reputation: 2931

If you only have a nested object so you can use

var array = [{
    "BEH": {
        "value": 2,
        "count": 4
    },
    "FHT": {
        "value": 4,
        "count": 1
    }
}]

var map1 = array.map(item => {
    var result = {};
    Object.keys(item).forEach(key => {
        result[key] = item[key].value
    })
    return result;
});

console.log(map1);
// expected [{BEH: 2, FHT: 4}]

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

This will give you both of your required results:

const x = {
  "array": [{
    "BEH": {
      "value": 2,
      "count": 4
    },
    "FHT": {
      "value": 4,
      "count": 1
    }
  }]
};

const result1 = x.array.flatMap(v => Object.values(v).map(({value}) => value));
const result2 = x.array.flatMap(v => Object.entries(v)).reduce((a, [key, {value}]) => (a[key] = value, a), {});

console.log(result1);
console.log(result2);

If your array always just has a single object, you could remove a lot of the complexity.

Upvotes: 1

Nikhil
Nikhil

Reputation: 6643

You can use Object.entries() to do that. I'm assuming your array always has just one element.

var data = { "array": [{ "BEH": { "value": 2, "count": 4 }, "FHT": { "value": 4, "count": 1 } }] }; 

var result = [];

Object.entries(data.array[0]).forEach(([key, value]) => {
  result.push({
    [key]: value.value
  });
});

console.log(result);

Upvotes: 0

Related Questions