将所选单词计入JS中的新对象

时间:2017-01-11 12:24:55

标签: javascript arrays object key

我有:

#!/usr/bin/env bash

# Custom `select` implementation that prints the menu items
# passed as arguments with reverse numbering, prompts for a selection,
# and outputs the selected item.
customSelect() {

  local item i=0 numItems=$# 

  # Print menu items with reverse numbering.
  for item; do
    printf '%s\n' "$((numItems - i++))) $item"
  done >&2 # Print to stderr, as `select` does.

  # Prompt the user for the index of the desired item.
  while :; do
    printf %s "${PS3-#? }" >&2 # Print the prompt string to stderr, as `select` does.
    read -r index
    # Make sure that a valid index was entered.
    (( index >= 1 && index <= numItems )) || { echo "Invalid selection." >&2; continue; }
    break
  done

  # Determine selected item by index entered and print it to stdout.
  printf %s "${@: numItems - index + 1 : 1}"

}

# Present the custom menu and prompt for a selection.
selectedItem=$(customSelect "$@")

# Process the selected item.
case $selectedItem in
  # YOUR HANDLERS HERE.
  *) # Sample handler
    echo "Selected item: [$selectedItem]"
    ;;
esac

应返回仅包含相互存在的键/值的新对象:

function selectMutualKeys(arr, obj) {
  var o = {};
  for (var i = 0; i < arr.length; i++) { 
    var key = arr[i];  
    if ( arr[i] === obj[key] ) {
      o[key] = obj[key] ;
    }
  }
  return o;
}

我缺少什么?

2 个答案:

答案 0 :(得分:1)

您可以使用in operator检查密钥是否为对象的属性,然后分配值。

if (key in obj) {

&#13;
&#13;
function selectMutualKeys(arr, obj) {
    var o = {}, key, i;
    for (i = 0; i < arr.length; i++) { 
        key = arr[i];  
        if (key in obj) {
            o[key] = obj[key];
        }
    }
    return o;
} 

var arr = ['a', 'c', 'e'],
    obj = { a: 1, b: 2, c: 3, d: 4 },
    out = selectMutualKeys(arr, obj);

console.log(out); // { a: 1, c: 3 }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
function selectMutualKeys(arr, obj) {
var o = {};
for (var i = 0; i < arr.length; i++) { 
  var key = arr[i];  
  if (obj[key] ) {
      o[key] = obj[key] ;
  }
}
return o;
} 


  var arr = ['a', 'c', 'e'];
  var obj = { 'a': 1, b: 2, c: 3, d: 4};
  var out = selectMutualKeys(arr, obj);
  console.log(out); // --> { a: 1, c: 3 } 
&#13;
&#13;
&#13;