簡體   English   中英

如何將數組值作為對象鍵傳遞,並將該鍵與對象中的某些值相關聯。 然后將其傳遞給列表項

[英]how to pass an array value as an object key, and associate that key with some values in the object. and then pass it into a list item

我試圖將數組值作為對象的鍵傳遞,並且在該對象中,每個鍵有兩個值,然后我想將它傳遞給列表項。 我該怎么做 這是我到目前為止所嘗試的:


'use strict';

const bookTitles = [
  'harry_potter_chamber_secrets',
  'small_island',
  'spook_street',
  'war_and_peace',
  'don_quixote',
  'a_tale_of_two_cities',
  'the_lord_of_the_rings',
  'harry_potter_and_the_secret_stone',
  'and_then_there_were_none',
  'the_hobbit',
];

console.log(bookTitles);

function booksInfoF(array) {
  for (var i = 0; i < array.length; i++){


    var booksInfoTrial = { array[i]: [{ author: 'somebody', language: 'english'}]}
  }

  return booksInfoTrial;

}

var outPut;
 outPut.booksInfoF(bookTitles);

listNode = document.createElement('ul');
liNode = document.createElement('LI');
textNode = document.createTextNode(outPut);

liNode.appendChild(textNode);
listNode.appendChild(liNode);

我的解決方案。

 var obj = [ 'harry_potter_chamber_secrets', 'small_island', 'spook_street', 'war_and_peace', 'don_quixote', 'a_tale_of_two_cities', 'the_lord_of_the_rings', 'harry_potter_and_the_secret_stone', 'and_then_there_were_none', 'the_hobbit', ].reduce((ac, cv, i) => Object.assign(ac, {[cv] : [{author: 'somebody', language: 'english'}]}), {}); console.log(obj); 

希望它會對你有所幫助。

你在找這個嗎?

 <!DOCTYPE html> <html> <body> <ul id="myList"> </ul> <p>Click the button to append an item to the end of the list.</p> <button onclick="myFunction()">Try it</button> <script> var books = [ 'harry_potter_chamber_secrets', 'small_island', 'spook_street', 'war_and_peace', 'don_quixote', 'a_tale_of_two_cities', 'the_lord_of_the_rings', 'harry_potter_and_the_secret_stone', 'and_then_there_were_none', 'the_hobbit', ].reduce((ac, cv, i) => Object.assign(ac, {[cv] : {author: 'somebody', language: 'english'}}), {}); function myFunction() { var UL = document.createElement("UL"); for(bookname in books){ var book_name = bookname.split('_').join(' ').toUpperCase(); var book = books[bookname]; var LI = document.createElement("LI"); var TX = document.createTextNode(book_name); LI.appendChild(TX); UL.appendChild(TX); var _UL = document.createElement("UL"); var I1 = document.createElement("LI"); var t1 = document.createTextNode('author: '+book.author); I1.appendChild(t1); var I2 = document.createElement("LI"); var t2 = document.createTextNode('language: '+book.language); I2.appendChild(t2); _UL.appendChild(I1); _UL.appendChild(I2); UL.appendChild(document.createElement("LI").appendChild(_UL)); } document.getElementById("myList").appendChild(UL); } </script> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM