以编程方式将值推入一个空对象

时间:2018-11-14 07:37:33

标签: javascript jquery

是否可以将值推入空的object中?我这里是显示国家名称和人口的国家/地区列表。我想将这些值插入对象,就像下面的示例一样。

<ul class="countries">
    <li  class="country">
        <span class="country-name">Philippines</span>
        <span class="country-population">200</span>
        <span class="description">Blablabla</span>
    </li>
    <li class="country">
        <span class="country-name">Brunei</span>
         <span class="country-population">200</span>
         <span class="description">Blablabla</span>
     </li>
     <li class="country">
         <span class="country-name">Malaysia</span>
         <span class="country-population">400</span>
         <span class="country-population">Blablabla</span>
     </li>

</ul>

var countries = [
    {name: "Philippines", population: 200, description: "Blablabla"},
    {name: "Brunei", population: 200, description: "Tatatata"},
    {name: "Malaysia", population:4100, description: 'Zzazazaza'}
]

0: {name: "Philippines", population: 200, description: "Blablabla"}
1: {name: "Brunei", population: 200, description: "Tatatata"}
2: {name: "Malaysia", population: 400, description: "Zzazazaza"}

我尝试了以下脚本,但只插入了国家名称。还如何插入populationdescription值?

var countries_new = [];

$('.countries > .country > .country-name').each(function() {
    countries_new.push({
        name: $(this).text()                
    });
}); 

6 个答案:

答案 0 :(得分:5)

您可以使用find()获取循环中每个上下文的引用。还要注意,+的前缀是将文本更改为数字类型。您也可以在此处使用parseInt()。使用trim()将有助于删除对象中多余的前导和尾随空格。

var countries = [];
$('.countries .country').each(function(){
  var countryRef = $(this);
  countries.push({
    name: countryRef.find('.country-name').text().trim(),
    population: +(countryRef.find('.country-population').text().trim()),
    description: countryRef.find('.description').text().trim()
  });
});
console.log(countries);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="countries">
  <li class="country">
    <span class="country-name">Philippines</span>
    <span class="country-population">200</span>
    <span class="description">Blablabla</span>
  </li>
  <li class="country">
    <span class="country-name">Brunei</span>
    <span class="country-population">200</span>
    <span class="description">Blablabla</span>
  </li>
  <li class="country">
    <span class="country-name">Malaysia</span>
    <span class="country-population">400</span>
    <span class="country-population">Blablabla</span>
  </li>

</ul>

答案 1 :(得分:4)

改为在.country元素上循环,然后在每个 find中的.country元素以及其他信息。根据模拟数组,population似乎是数字,而text()返回 string ,请使用Number()进行转换。

var countries_new = [];

$('.countries > .country').each(function() {
    countries_new.push({
        name: $(this).find(".country-name").text(),
        population: Number($(this).find(".country-population").text()),
        description: $(this).find(".description").text()
    });
});

console.log(countries_new);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="countries">
        <li  class="country">
            <span class="country-name">Philippines</span>
            <span class="country-population">200</span>
            <span class="description">Blablabla</span>
        </li>
        <li class="country">
            <span class="country-name">Brunei</span>
            <span class="country-population">200</span>
            <span class="description">Blablabla</span>
        </li>
        <li class="country">
            <span class="country-name">Malaysia</span>
            <span class="country-population">400</span>
            <span class="description">Blablabla</span>
        </li>

    </ul>

答案 2 :(得分:1)

您不需要jQuery,只需选择所有国家/地区,然后从该元素中选择所需的值即可。

console.log(
  [...document.querySelectorAll('.countries>.country')].map(
    (el) => ({
      name: el.querySelector('.country-name').innerText.trim(),
      population: el.querySelector('.country-population')
        .innerText.trim(),
      description: el.querySelector('.description')
        .innerText.trim(),
    }),
  ),
);
<ul class="countries">
    <li  class="country">
        <span class="country-name">Philippines</span>
        <span class="country-population">200</span>
        <span class="description">P Blablabla</span>
    </li>
    <li class="country">
        <span class="country-name">Brunei</span>
        <span class="country-population">200</span>
        <span class="description">B Blablabla</span>
    </li>
    <li class="country">
        <span class="country-name">Malaysia</span>
        <span class="country-population">400</span>
        <span class="description">M Blablabla</span>
    </li>

</ul>

答案 3 :(得分:1)

假设您所有的span元素都具有以country-开头的CSS类,这将是一种通用方法:

const countries = document.querySelectorAll('.country');

const result = [];

for (const country of countries) {
  let resEl = {};
  [...country.querySelectorAll('span[class^="country-"]')].forEach((span) => resEl[span.className.split('-')[1]] = span.innerText)
  result.push(resEl);
}

console.log(result)
<ul class="countries">
  <li class="country">
    <span class="country-name">Philippines</span>
    <span class="country-population">200</span>
    <span class="country-description">Blablabla</span>
  </li>
  <li class="country">
    <span class="country-name">Brunei</span>
    <span class="country-population">200</span>
    <span class="country-description">Blablabla</span>
  </li>
  <li class="country">
    <span class="country-name">Malaysia</span>
    <span class="country-population">400</span>
    <span class="country-description">Blablabla</span>
  </li>
</ul>

答案 4 :(得分:1)

您实际上没有将值推入一个空对象中,而是希望创建一个对象并将该对象推入数组中。因此,基本上,您可以使用数组映射方法来返回数组。

仅使用JavaScript,您可以使用document.querySelectorAll来选择具有指定选择器(在这种情况下为类)的所有元素。[...]使用传播语法将实时集合转换为数组,以便使用数组方法可以使用。这里map是一个数组方法。在此方法内创建一个对象并返回该对象

let k = [...document.querySelectorAll('.country')].map(function(curr) {
  return {
    name: curr.querySelector('.country-name').textContent.trim(),
    population: curr.querySelector('.country-population').textContent.trim(),
    description: curr.querySelector('.description').textContent.trim()

  }
})

console.log(k)
<ul class="countries">
  <li class="country">
    <span class="country-name">Philippines</span>
    <span class="country-population">200</span>
    <span class="description">Blablabla</span>
  </li>
  <li class="country">
    <span class="country-name">Brunei</span>
    <span class="country-population">200</span>
    <span class="description">Blablabla</span>
  </li>
  <li class="country">
    <span class="country-name">Malaysia</span>
    <span class="country-population">400</span>
    <span class="description">Blablabla</span>
  </li>

</ul>

答案 5 :(得分:-1)

另一种简短但有效的方法。

"use strict";
function _toConsumableArray(a) {
  if (Array.isArray(a)) {
    for (var b = 0, c = Array(a.length); b < a.length; b++) c[b] = a[b];
    return c;
  }
  return Array.from(a);
}
var results = []
  .concat(_toConsumableArray(document.querySelectorAll(".countries>.country")))
  .map(function(a) {
    return {
      name: a.querySelector(".country-name").innerText.trim(),
      population: a.querySelector(".country-population").innerText.trim(),
      description: a.querySelector(".description").innerText.trim()
    };
  });
console.log(results);