将推送元素拆分为Javascript空数组

时间:2017-07-20 11:04:56

标签: javascript html arrays

我有一个名为result []的空数组。然后,用户单击一个链接,该链接调用一个名为getId()的函数,该函数传递单击的id以检查它是否与另一个名为productsArray []的数组中的id匹配。

<a href="javascript:void(0)" class="abc" onClick="getId(this.id)">Jackets</a>

var productsArray = [
    {id:0, title:"Product A",description:"description 0"}, 
    {id:0, title:"Product B",description:"description 1"}, 
    {id:2, title:"Product C",description:"description 2",}, 
    {id:0, title:"Product D",description:"description 3",},  
    {id:4, title:"Product A",description:"description 4",}, 
    {id:5, title:"Product A",description:"description 5",}
],
result = [];

如果用户点击Jackets链接(其id为0),productArray中的3个项目将返回:产品A,B和D.

我必须实现的代码才有效:

var output;
var container;

for(key in productsArray) { 

    if (productsArray[key].id == id) { 
       result.push(productsArray[key].title, productsArray[key].description); 
    }
}

container = document.getElementById('content');
output=result;
container.innerHTML=output;

<div id="content"></div>

但问题是所有数据都分配给result []键索引:

例如:

[0]Produduct A title
[1]Product B title
[2]Product C title

我想要实现一种按以下方式分割数据的方法:

output+= result[0].title + result[0].description

任何帮助表示感谢。

干杯

2 个答案:

答案 0 :(得分:1)

您必须分配一个带有标题和描述值的变量,然后将该值推送到数组。如下面的代码

function getId(id){
var output;
var container;
for(key in productsArray) { 
 if (productsArray[key].id == id) { 
newObj= "" ; // assign to blank
newObj = productsArray[key].title +" "+ productsArray[key].description; //assign as per you need the format
result.push(newObj);  // push it to array
    }
}

container = document.getElementById('content');
output=result;
container.innerHTML=output;}

答案 1 :(得分:1)

您可以映射产品的结果和所需的密钥。

&#13;
&#13;
function getId(id) {
    document.getElementById('content').innerHTML = productsArray
        .filter(function (product) {
            return product.id == id;
        })
        .map(function (product) {
            return ['title', 'description']
                .map(function (key) { return product[key]; })
                .join(' ');
        })
        .join('<br>');
}

var productsArray = [{ id: 0, title: "Product A", description: "description 0" }, { id: 0, title: "Product B", description: "description 1" }, { id: 2, title: "Product C", description: "description 2" }, { id: 0, title: "Product D", description: "description 3" }, { id: 4, title: "Product A", description: "description 4" }, { id: 5, title: "Product A", description: "description 5" }];
&#13;
<a href="javascript:void 0" onclick="getId(0)">Jackets</a>
<div id="content"></div>
&#13;
&#13;
&#13;