1

I have JSON data:

users = [{
  "name": "alex", 
   "id":123, 
   "surname":"xx", 
    tarriff: {
      "id":1,
      "name":"free"
    }
},
 {
  "name": "tom", 
   "id":124, 
   "surname":"henry", 
    tarriff: {
      "id":1,
      "name":"free"
    }
}

]

I need to filter the data (remove "surname":"xx", "surname":"henry" and smt else ).

If I use tarriff.name that's give syntax error

$scope.userfilter = users.map(({name,id, tarriff.name}) => ({name, id, tariff_name}));

help me please write the right solution.

0

3 Answers 3

1

You could take a destructuring assignment and build a new object with short hand properties.

var users = [{ name: "alex", id: 123, surname: "xx", tarriff: { id: 1, name: "free" } }, { name: "tom", id: 124, surname: "henry", tarriff: { id: 1, name: "free" } }],
    result = users.map(({ name, id, tarriff }) => ({ name, id, tarriff_name: tarriff.name }));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

0

Your users variable is an object, not array. I assume this is just a mistake here and you want to know how to filter an array. You should use filter method like this:

const users = [
  {"name": "alex", "id":123, "surname":"xx", tarriff:{"id":1,"name":"free"}},
  {"name": "emma", "id":123, "surname":"yy", tarriff:{"id":2,"name":"anna"}}
];

const criterium = "free";
const matchingUsers = users.filter(user => user.tarriff.name == criterium);

console.log (matchingUsers)

Comments

0

it is hard to understand what you really want. but I am guessing that you are not talking about Array.filter and rather mapping deeply.

the syntax error is because you are de-structuring wrong. here is a better way :

$scope.userfilter = users.map( ({name, id, tarriff: { name: tarriff_name }}) => {
    return {name, id, tariff_name};
});

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.