How to feed a JSON using "for" Javascript

Asked

Viewed 193 times

-4

I have a json in Javascript:

var cards = [
 {
    name: "Opção 1",
    img: "images/opcao1.jpg",
    id: "1"
 },
 {
    name: "Opção 2",
    img: "images/opcao2.jpg",
    id: "2"
 },
 {
    name: "Opção 3",
    img: "images/opcao3.jpg",
    id: "3"
 }              
        ];

My question is, how could I edit or add items to this json using for? The use of the for would be why I receive via Ajax values to be fed.

  • Let me see if I understand. Do you want to do a lopping with FOR to sweep your Ajax? Would that be it?

  • Actually I want to fill in with more values, creating the Indice 4, 5, 6 etc

1 answer

3

What you have is an array, not a JSON. JSON is the only form of Javascript-based object notation. Saying you have a JSON means you have a string with the JSON notation:

const meuJSON = '{"nome": "Usuário"}'.

To power your array, you just need to do push in it. jQuery Ajax (according to its tag) already converts the received JSON to object, example:

var cards = [{
  userId: 0,
  id: 0,
  title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
}]

$.getJSON('https://jsonplaceholder.typicode.com/posts/1')
  .done(function(data) {
    console.log('dados recebidos do ajax:', data)
    cards.push(data)
    console.log('meus cards com o ajax:', cards)
  })
  .fail(function() {
    console.log('Ops! Um erro aconteceu')
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Thank you for the answer, but in your code it is understood that the json I will receive is from the same array structure. the JSON I receive is that structure totally different, so my question of how to set determine JSON value received to a specific position of the array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.