简体   繁体   English

匹配JavaScript中的两个数组或对象

[英]match two arrays or objects in javascript

I have two javascript objects 我有两个JavaScript对象

var category = new Object();

I add some attributes to the object as 我添加一些属性到对象为

category.Hot = "Red";
category.Cold = "Blue";
category.Warm = "Yellow";

I have another object which holds the id, category value and some other attributes 我有另一个对象,其中包含ID,类别值和其他一些属性

var categorization = [];

categorization = {"id1 : Hot","id2 : Cold","id3 : Hot","id4 : Warm"},

Now I need to map all the items in categorization with their appropriate color in category. 现在,我需要使用适当的颜色在类别中映射所有分类的项目。 I need something like this. 我需要这样的东西。

var combinedResult = null;

combinedResult.id1 = {'Hot : Red'}
combinedResult.id2 = {'Cold : Blue'}
combinedResult.id3 = {'Hot : Red'}
combinedResult.id4 = {'Warm : Yellow'}

I'm new to javascript so there may be syntactical errors. 我是javascript新手,因此可能存在语法错误。 I have achieved the same in C# any go ahead tips would be appreciated. 我已经在C#中实现了相同的目标,任何继续前进的技巧都将不胜感激。

You may do it this way: 您可以这样进行:

$.each(categorization,function(id, val){
    var tempObj = {};
    tempObj[val] = category[val];

    combinedResult[id] = tempObj;
});

Here's sample Fiddle . 这是样本小提琴

Wouldn't something along the lines of the below be easier for you? 难道以下内容对您来说更容易吗?

var categorization = [];

categorization.push({"Id" : "Hot","colour":"Red"});
categorization.push({"Id" : "Cold","colour":"Blue"});
categorization.push({"Id" : "Warm","colour":"Yellow"});

Then 然后

categorization[0].Id, categorization[0].colour etc...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM