I would like to know how to implement object first and later mergeObject in javascript.

I have inputs as shown in which i want to display the myList first then after 4 seconds, display the mergeList . How to implement using javascript

how to display original listmyList and display loading image for 4 seconds and show mergeList mergeList

Inputs
var myList =[{ 
  id: "trans",  
  value: "200",
  fee: "2"
}]

var translist= [{
  id: "trans",
  cn: "SG",
  rate: "0.5",
  fee: "4" 
}]

function mergeList(){
  myList.forEach((e)=>{
    if(e.id == "trans"){
      Object.assign(e, translist)
      e.amount = (e.value *e.rate) + e.fee
    }
  })
}
//here myList overrides already existed object  
var mergeList =this.mergeList();


<div>
  ${myList.map((e) => {

  return html`<p>${e.id}</p> <h5>${e.amount}</h5>  `

  })}
</div>

2 Answers

0
ray hatfield On Best Solutions

const myList =[{ 
  id: "trans",  
  value: 200, // don't quote numbers
  fee: 2 // don't quote numbers
}]

const trans = { // an object, not an array
  id: "trans",
  cn: "SG",
  rate: 0.5, // don't quote numbers
  fee: 4 // don't quote numbers
};

// merge in the trans props where appropriate
const merged = myList.map(item => (
  item.id === 'trans'
    ? {...item, ...trans}
    : item
 ));

// generate an html string for a list item
function renderItem (item) {
  return `
    <div>
      <p>${item.id}</p>
      <h5>${item.value + (item.rate || 0) + item.fee}</h5>
    </div>
  `;
}

// display the specified list
function renderList (list) {
  document.getElementById('list').innerHTML = list.map(renderItem).join();
}

// display the initial list
renderList(myList);

// display the merged list afer 4 seconds (4000ms)
setTimeout(() => {
  renderList(merged);
  document.getElementById('list').classList.remove('loading');
 }, 4000);
#list {
  position: relative;
}

.loading::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url('https://d.pr/f/YQKfWe+');

  background-repeat: no-repeat;
  background-position: center left;
}
<div id="list" class="loading">
</div>

0
Community On

Try setTimeout

//here myList overrides already existed object  
function waitSeconds(seconds) {
    setTimeout(mergeList, seconds);
}

this.waitSeconds(4000);