0

I've below Json object that contain car associated to their manufacturer. From Json object, I want to get total number of cars as well as occurrence of a specific car in the object.

var Cars = { "manufacturer":"Car":
               [{"Saab":"Automobile AB"},
                {"Volvo":"V40"},
                {"BMW":"Estoril Blue"},
                {"Volvo":"V40"},
              ]};

I tried to use the filter but since filter is only specific for Arrays so cannot used it with Json object. Below is the source code.

var Cars = {"manufacturer":"Car":
               [{"Saab":"Automobile AB"},
                {"Volvo":"V40"},
                {"BMW":"Estoril Blue"},
                {"Volvo":"V40"},
               ]};

var volvo = "V40";

var numberOfCars = Cars.filter(function (x) {
       return x === volvo;
    }).length;

I expect the output of the above source code as 2. But I get an exception

Cars.filter is not a function

I need you guys to please help me to get the occurrence of V40 (that is 2), as well as total number of cars (which are 4).

2
  • 2
    1) You can't have same key twice on same object, 2) filter is method on arrays not object Commented Jun 20, 2019 at 15:42
  • I just updated Json object. Commented Jun 20, 2019 at 15:58

2 Answers 2

1

It's easy enough to walk over the properties of an object. One way is to use Object.entries to get an array of the properties and values;

var Cars = [{"Saab":"Automobile AB"}, {"Volvo":"V40"}, {"BMW":"Estorill Blue"}, {"Volvo":"V40"}];

let properties = Object.entries(Cars);
console.log("Number of cars: ", Cars.length);
console.log("Number of Volvos: ", Cars.filter((car) => Object.keys(car)[0] === "Volvo").length);

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

3 Comments

Please add duplicate cars in Json object to get its more than one occurrences.
I've created the Cars array as above, I'm hoping this matches your data.. thanks!
Or is the cars array a property of the Cars object? The input is slightly confusing! :)
0

Use filter and then you can create object which has the duplicate car name as key and its number of occurences as val.

const input = [{"Saab":"Automobile AB"}, {"Volvo":"V40"}, {"BMW":"Estorill Blue"}, {"Volvo":"V40"}];

const volvo = "V40";

const duplicateCars = input.filter(({Volvo}) => volvo == Volvo);

const duplicateCarName = Object.keys(duplicateCars[0])[0];

console.log({[duplicateCarName]:duplicateCars.length});

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.