javascript - JS根据key值拼接数组值

标签 javascript html css arrays

下面的代码由三个不同的数组组成 Red Fruits、Green Fruits 和 Suggested Fruits通过单击值到 Green Fruits,反之亦然。但现在我正在尝试做一些不同的事情,它使用我的新 Multidimensional Array: fruits 拼接并将 suggestFruits 数组的值推送到我的 redgreen fruits 数组取决于 type 例如type:1 转到red fruits 表,type:2 转到green fruits 表 有没有简单的方法完成这个?任何帮助将不胜感激!

var red = {};
var green = {};
var random = {};
var fruits = [];

var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}

fruits.push(fruits1,fruits2,fruits3,fruits4);
console.log(fruits);

var suggestFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
console.log(suggestFruits);

var key = "Red Fruits";
red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'];

var key2 = "Green Fruits";
green[key2] = ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'];

var key3 = "Random Fruits";
random[key3] = suggestFruits;

 function redraw() {
     var redString = '';
     $.each(red[key], function(index) {
         redString += ('<div class="pilldiv redpill class">' + red[key][index] + '</div>');
     });
     $('.redclass').html(redString);

     var greenString = '';
     $.each(green[key2], function(index) {
         greenString += ('<div class="pilldiv greenpill class">' + green[key2][index] + '</div>');
     });
     $('.greenclass').html(greenString);

     var randomString = '';
     $.each(random[key3], function(index) {
         randomString += ('<div class="pilldiv randompill class">' + random[key3][index] + '</div>');
     });
     $('.randomclass').html(randomString);
	}
	
 function listener() {
	 
	$(document).ready(function() {
    $(document).on("click", "#randomid div", function() {
            data = this.innerHTML;
			k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
            index = random[k1].indexOf(data);
            random[k1].splice(index, 1);
            green[key2].push(data);
            $(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
            var element = $(this).detach();
            $('#greenid').append('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
          });
      });
	  
	   $('body').on('click', 'div.new-green-fruit', function() {
        data2 = this.innerHTML;
		console.log(data2);
		k2 = Object.keys(green).find(k => green[k].indexOf(data2) >= 0)
        index2 = green[k2].indexOf(data2);
        green[k2].splice(index2, 1);
        random[key3].push(data2);
        $(this).detach();
        var element2 = $(this).detach();
        $('#randomid').append('<div class="pilldiv randompill class" >' + element2.html() + '</div>');
	   });
	}
	redraw();
	listener();
.pilldiv {
  padding: 8px 15px;
  text-align: center;
  font-size: 15px;
  border-radius: 25px;
  color: Black;
  margin: 2px;
}

.redpill {
  background-color: Pink;
  cursor:default;
}
.greenpill {
  background-color: SpringGreen;
    cursor:default;

}
.randompill {
  background-color: LightBlue;
    cursor:pointer;
}
 .class {
  font-family: Open Sans;
}
.center {
  display: flex;
  justify-content: center;
}
.wrappingflexbox {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
.top {
	margin-bottom: 20px
}
h3{
font-weight: normal;
}
.panel {
    display: table;
    height: 100%;
    width: 60%;
	background-color:white;
	border: 1px solid black;
	margin-left: auto;
    margin-right: auto;
}
.new-green-fruit{
background-color: LightBlue;
cursor:pointer;
}
.top{
margin-bottom:30px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="//#" />

</head>

<body>
    <div class="panel">
        <div style="float:left;width:calc(50% - 5px);">
            <h3 class="class center">Red Fruits</h3>
            <div id="redid" class="redclass wrappingflexbox top"></div>
        </div>

        <div style="float:right;width:calc(50% - 5px)">
            <h3 class="class center">Green Fruits</h3>
            <div id="greenid" class="greenclass wrappingflexbox top"></div>
        </div>

        <div style="clear:both">
            <h3 class="center class">Suggested Fruits</h3>
            <div id="randomid" class="randomclass wrappingflexbox top"></div>
        </div>
    </div>

    </body>
</html>

最佳答案

这个问题涉及很多内容,但根据我收集到的信息,您只是在尝试将 type === "1" 的水果名称推送到红色水果数组, 并且 type === "2" 到绿色水果数组。

suggestedFruits 分成红色和绿色类别的主要问题是,当您创建 suggestedFruits 数组时,您将丢失 type 信息。不过,您可以做的是回头查看原始 fruits 数组以获取信息。

以下是实现该目标的方法:

var fruits = [
  {fruit:"Apple", type:"1"},
  {fruit:"Tomato", type:"1"},
  {fruit:"Lime", type:"2"},
  {fruit:"Guava", type:"2"},
];
// map so we can know how to map fruit.type into the correct fruitTypes array
var fruitTypeMap = {"1": "Red Fruits", "2": "Green Fruits"}
// one container for all fruit types so we can access dynamically
var fruitTypes = {
  "Red Fruits": ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'],
  "Green Fruits": ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'],
  "Random Fruits": fruits.map(fruit => fruit.fruit)
};
// clone element for easily creating fruit-pills
var clonePill = $(".clone");
// initialize the red/green/random pills
Object.keys(fruitTypes).forEach(key => {
  fruitTypes[key].forEach(fruit => {
    var $newFruit = clonePill.clone();
    // remove clone class so it is visible and doesn't get re-cloned
    $newFruit.removeClass("clone");
    // set the text
    $newFruit.text(fruit);
    // append to the correct list in DOM
    $(`[data-fruits="${key}"]`).append($newFruit);
  });
});

// handler for moving a fruits back and forth
function moveFruit (e) {
  // get the category from the data-fruits property on the parent container
  var fruitCategory = $(this).parent().data("fruits");
  var fruitName = $(this).text();
  // detach the fruit element from the DOM and keep it in a variable so we can re-insert later
  var $fruit = $(this).detach();
  if (fruitCategory === "Random Fruits") {
    // get the type number from the original fruits array
    var fruitType = fruits.find(fruit => fruit.fruit === fruitName).type;
    // find the correct array to place the fruit into
    var fruitArr = fruitTypes[fruitTypeMap[fruitType]];
    // find the index of the array it is currently in
    var fruitIndex = fruitTypes["Random Fruits"].indexOf(fruitName);
    // splice out of current array and insert into destination array in 1 line
    fruitArr.push(fruitTypes["Random Fruits"].splice(fruitIndex, 1)[0]);
    // add movable class so we can toggle it back to Random Fruits on click
    $fruit.addClass("movable");
    // finally, add to the correct list in the DOM
    $(`[data-fruits="${fruitTypeMap[fruitType]}"]`).append($fruit); 
  }
  else {
    // find the current array
    var fruitArr = fruitTypes[fruitCategory];
    // find the index of the fruit in the current array
    var fruitIndex = fruitArr.indexOf(fruitName);
    // splice out of current array and insert into destination array in 1 line
    fruitTypes["Random Fruits"].push(fruitArr.splice(fruitIndex, 1)[0]);
    // add back to Random Fruits list
    $('[data-fruits="Random Fruits"]').append($fruit); 
  }
}
// handle click on all fruits that we label as .movable in the red/green lists
$(".red-fruits, .green-fruits").on("click", ".movable", moveFruit);
// handle click on all items in Random Fruits list
$(".random-fruits").on("click", ".fruit-pill", moveFruit);
.clone {
  display: none;
}
.fruit-pill {
  border-radius: 20px;
  padding: 10px 15px;
  display: inline-block;
}
.movable {
  cursor: pointer;
}
.red-fruits > .fruit-pill {
  background-color: rgba(255, 0, 0, 0.6);
}
.red-fruits > .movable {
  background-color: rgb(255, 150, 150);
}
.green-fruits > .fruit-pill {
  background-color: rgba(0, 255, 0, 0.7);
}
.green-fruits > .movable {
  background-color: rgb(200, 255, 175);
}
.random-fruits > .fruit-pill {
  background-color: rgba(0, 0, 0, 0.2);
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fruits-container">
  <div class="red-fruits" data-fruits="Red Fruits">
  </div>
  <div class="green-fruits" data-fruits="Green Fruits">
  </div>
  <div class="random-fruits" data-fruits="Random Fruits">
  </div>
</div>
<div class="fruit-pill clone"></div>

关于javascript - JS根据key值拼接数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50972662/

相关文章:

javascript - JSTree - 添加 Action 重定向

javascript - 删除 chart.js 中的雷达图标签

javascript - react-native-table-component 卡住可滚动表中的第一列和第一行

html - 如何防止网页缩放

html - 放大时剪切背景图像

css - asp.net mvc 默认元素中的 html css

javascript - jquery队列自动搜索现有用户

javascript - 选中复选框时调用函数,取消选中时不会触发 onclick 事件

html - 减少 Bootstrap 的列间距

javascript - 使用带有 Prev 和 Next 图标的 Jquery 滚动到下一个 Div