1

My Data from API looks like below,

[
  {
    "id": 1,
    "appName": "string",
    "defaultAction": "string",
    "defaultMessage": "string",
    "rules": [
      {
        "id": 1,
        "version": "string",
        "brand": "string",
        "action": "string",
        "message": "string"
      },
      {
        "id": 2,
        "version": "string",
        "brand": "new brand",
        "action": "string",
        "message": "string"
      }
    ]
  }
]

I tried like below to read child array from Parent Array from State to bind to table

const { posts } = this.state;
console.log(posts);
   const rule_list = posts.map(rules => {
  console.log(rules);
});

But I see it still returns complete array rather than only child element.Can someone help me here.

1
  • What console.log(posts); is prints Commented Apr 12, 2019 at 6:37

2 Answers 2

2

Rules is complete element at particular index, You need to access the property you want to access i.e rules.rules

Or you can Destructuring_assignment

let data = [ { "id": 1, "appName": "string", "defaultAction": "string", "defaultMessage": "string", "rules": [ { "id": 1, "version": "string", "brand": "string", "action": "string", "message": "string" }, { "id": 2, "version": "string", "brand": "new brand", "action": "string", "message": "string" } ] } ]

const rule_list = data.map(({rules}) => {
  console.log(rules);
});

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

1 Comment

Hi, if I have 2 parent nodes and child nodes then its returning all the child nodes of both parent nodes. Anything missing here? my API results like below [ { "id": 1, "rules": [ { "id": 1, }, { "id": 2, } ] }, { "id": 2, "rules": [] } ]
0

You need to access rules property of each post item to get the child rules array as below.

posts.map((post) => {
   console.log(post.rules);
});

if you want to form a rules array from all posts, you can do that as below:

const rule_list = posts.map((post) => {
        let { rules } = post;
        if(rules && rules.length > 0) {
            return rules;
        }
    });
console.log(rule_list);

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.