0

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 
  }
]
its-me-mahmud
  • 690
  • 1
  • 7
  • 14

2 Answers2

0

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));
  • Hey Thank you for the help. I wrote this and it worked out. "document.write(JSON.stringify(twoYearOldCars));" – Eric Kholod Apr 26 '23 at 20:38
  • Also How come using document.write is the wrong method? – Eric Kholod Apr 26 '23 at 20:40
  • By using Document.write(), you don't have the hand of where the content is being inserted. Javascript will insert it as last node of Document Object. You must be clear when you write your code. – King Saozer Apr 27 '23 at 07:50
0

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>
Andy
  • 61,948
  • 13
  • 68
  • 95