提问者:小点点

如何通过迭代对象向对象添加新属性?


我想要得到一个这样的对象:

let newPost = {
   title: "Post 1",
   Content: "New content"
}

通过这样编码:

let newPost = {};

let postData = $(".post-data").each (function(index) {
    newPost.title = $(this).text()
    newPost.content = $(this).text()
})

    <h5 class="card-title post-data" data-title = "title">Post 1</h5>
    <p class="card-text post-data" data = "content">New content</p>

但我总是得到以下几点:

let newPost = {
   title = "New content",
   content = "New content"
}

共1个答案

匿名用户

为了完成所需的操作,您应该在每次循环迭代时更新每个属性,而不是同时更新所有属性。此外,您需要使data属性名称在所有目标元素中保持一致,以便它可以用作输出对象的键。记住这一点,试试这个:

null

let newPost = {};
$(".post-data").each((i, el) => newPost[el.dataset.key] = el.innerText.trim());

console.log(newPost);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h5 class="card-title post-data" data-key="title">Post 1</h5>
<p class="card-text post-data" data-key="content">New content</p>