skip to Main Content

Output:

enter image description here

My code:

let carsArray = [
  {
    make: "BMW",
    model: "325i",
    year: 2034,
  },
  {
    make: "Volvo",
    model: "540xi",
    year: 2025,
  },
  {
    make: "BMW",
    model: "435e",
    year: 1994,
  },
  {
    make: "BMW",
    model: "X6",
    year: 2025,
  },
];

function twoYearsOld (element) {
  let year = element.year - 2023;
  return year === 2;
};

let twoYearOldCars = carsArray.filter(twoYearsOld);
document.write(twoYearOldCars);

Hey Everyone. I have an issue where when I write document.write, the outcome on the live page just says object, object. I have an array with objects in it.

I am expecting it to say this:

[
  { 
    make: 'Volvo', 
    model: '540xi', 
    year: 2025 
  },
  { 
    make: 'BMW', 
    model: 'X6', 
    year: 2025 
  }
]

2

Answers


  1. I think, you are using a wrong method to display your result. you can use console.log() or JSON.stringify() like this

    1. With Console.log

      console.log(twoYearOldCars);

    2. With JSON.stringify()

      document.body.innerText = JSON.stringify(twoYearOldCars);

    Now let see how the code looks

    let carsArray = [
        {
          make: "BMW",
          model: "325i",
          year: 2034,
        },
        {
          make: "Volvo",
          model: "540xi",
          year: 2025,
        },
        {
          make: "BMW",
          model: "435e",
          year: 1994,
        },
        {
          make: "BMW",
          model: "X6",
          year: 2025,
        },
      ];
    
      function twoYearsOld (element) {
        let year = element.year - 2023;
        return year === 2;
      };
    
    let twoYearOldCars = carsArray.filter(twoYearsOld);
    
    console.log(JSON.stringify(twoYearOldCars));
    
    Login or Signup to reply.
  2. It sounds like you want to "prettify" the data. You can stringify it, and then add it to a <code> element inside a <pre> element. ref1 | ref2.

    let carsArray=[{make:"BMW",model:"325i",year:2034},{make:"Volvo",model:"540xi",year:2025},{make:"BMW",model:"435e",year:1994},{make:"BMW",model:"X6",year:2025}];
    
    function twoYearsOld(element) {
      return element.year - 2023 === 2;
    }
    
    const twoYearOldCars = carsArray.filter(twoYearsOld);
    
    const code = document.querySelector('code');
    
    // `stringify` accepts three arguments. The first is the data
    // you want to stringify, the third is the space indentation.
    // and the second is "the replacer" - you can read about
    // that in the documentaton
    code.textContent = JSON.stringify(twoYearOldCars, null, 2);
    <pre><code></code></pre>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search