JS根据键值拼接数组值

时间:2018-06-21 15:45:13

标签: javascript html css arrays

我下面的代码包含三个不同的数组Red Fruits, Green Fruits and Suggested Fruits,通过单击该值,可以将一个数组值从Suggested Fruits拼接到Green Fruits,反之亦然。但是现在我正在尝试做一些不同的事情,那就是使用新的Multidimensional Array: fruits来拼接suggestFruits数组的值并将其推入redgreen水果数组,具体取决于在type上,例如type:1进入red fruits表,type:2进入green fruits table,是否有任何简单的方法来实现?任何帮助将不胜感激!

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>

1 个答案:

答案 0 :(得分:3)

这个问题上有很多事情要做,但是从我收集到的信息来看,您只是试图将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>