объект не возвращает значение в JavaScript - PullRequest
0 голосов
/ 02 апреля 2019

Как получить значение объекта на основе комбинаций в javascript?

Я не знаю, как перебрать объект на основе входных данных, переданных в вызов функции, и получить значение объекта.Нужна некоторая помощь.

Ожидаемый результат должен быть таким, как показано ниже.

getValueCreditToBank(obj, "credit", "bank", "SGD");
getValueDebitToBank(obj, "debit", "bank", "THB");

Ниже код получает значение, но должен выполнять две функции, есть ли какой-либо метод, который можно выполнить в одном вызове функции,

// getValueCreditToBank(obj, "credit", "bank", "SGD");
function getValueCreditToBank(provider, typein, typeout, source){
  return provider.map(item => {
    if (item.country_from[0].paymentIn[0].type == typein 
        && item.country_from[0].currency.includes(source) 
        && item.country_from[0].paymentOut[0].type == typeout) {
      return {
        paymentIn: typein,
        paymentOut: typeout,
        paymentInFee: item.country_from[0].paymentIn[0].fee.number + "%",
        payInSpeed: item.country_from[0].paymentIn[0].speed.number + "days",
        ...item
      }      
    }
   })
  .map(y=>({  
    ...y,
    targetAmountwithPay: y.targetAmount + y.country_from[0].paymentIn[0].fee.number*y.targetAmount/100
  }))
}

// getValueDebitToBank(obj, "debit", "bank", "SGD");
function getValueDebitToBank(provider, typein, typeout, source){
  return provider.map(item => {
    if (item.country_from[0].paymentIn[1].type == typein 
        && item.country_from[0].currency.includes(source) 
        && item.country_from[0].paymentOut[0].type == typeout) {
      return {
        paymentIn: typein,
        paymentOut: typeout,
        paymentInFee: item.country_from[0].paymentIn[1].fee.number + "%",
        payInSpeed: item.country_from[0].paymentIn[1].speed.number + "days",
        ...item
      }      
    }
   })
  .map(y=>({  
    ...y,
    targetAmountwithPay: y.targetAmount + y.country_from[0].paymentIn[0].fee.number*y.targetAmount/100
  }))
}

Пример объекта:

var obj = [{
    "id": "identity1",
    "fee": '2',
    "rate": '0.5',
    "targetAmount": '1000',
     "country_from": [{
        "currency": [
            "SGD",
            "USD"
        ],
        "paymentIn": [{
            "type": "credit",
            "speed": {
                "unit": "days",
                "number": "1"
            },
            "fee": {
                "type": "%",
                "number": "1.5"
            }
        },{
            "type": "debit",
            "speed": {
                "unit": "days",
                "number": "1"
            },
            "fee": {
                "type": "%",
                "number": "1"
            }
        }],
       "paymentout":[{
          "type":"bank"
       }]
    }]
},
{
    "id": "identity2",
    "fee": '1',
    "rate": '0.5',
    "targetAmount": '1000',
     "country_from": [{
        "currency": [
            "THB",
            "USD"
        ],
        "paymentIn": [{
            "type": "debit",
            "speed": {
                "unit": "days",
                "number": "1"
            },
            "fee": {
                "type": "%",
                "number": "1"
            }
        }
        ],
       "paymentout":[{
          "type":"bank"
       }]
    }]
}]

Ожидаемый результат:

//getValue(obj, "credit", "bank", "SGD"); should return object as
 {id: "identity1",
 fee: '2',
 rate: '0.5',
 currency: SGD,
 paymentIn: "credit",
 paymentOut: "bank",
 paymentIn Fee: 1.5%,
 targetAmount: 1000,
 targetAmountwithPay: 506.485 //(((targetamount-fee)*rate)+credit fee))}
//getValue(obj, "debit", "bank", "THB"); should return object as
 {id: "identity2",
 fee: '1',
 rate: '0.5',
 currency: THB,
 paymentIn: "debit",
 paymentOut: "bank",
 paymentIn Fee: 1%,
 targetAmount: 1000,
 targetAmountwithPay: 504.49 //(((targetamount-fee)*rate)+credit fee))}

Ответы [ 2 ]

1 голос
/ 02 апреля 2019

Первая проблема, которую я вижу с вашим кодом, заключается в том, что вы отображаете весь массив, но изменяете только некоторые элементы.

Возможно, вы этого не заметили, потому что фильтр, который вы установили, пропускает все элементы массива, но если этого не произойдет, вы увидите множество неопределенных в вашем окончательном массиве.

Поэтому я предлагаю вам обновить код, добавив фильтр:

function getValueCreditToBank(provider, typein, typeout, source){
  return provider
    .filter(item => (item.country_from[0].paymentIn[0].type == typein 
        && item.country_from[0].currency.includes(source) 
        && item.country_from[0].paymentOut[0].type == typeout))
    .map(item => ({
        paymentIn: typein,
        paymentOut: typeout,
        paymentInFee: item.country_from[0].paymentIn[0].fee.number + "%",
        payInSpeed: item.country_from[0].paymentIn[0].speed.number + "days",
        ...item
      }))
  .map(y=>({  
    ...y,
    targetAmountwithPay: y.targetAmount + y.country_from[0].paymentIn[0].fee.number*y.targetAmount/100
  }))
}

Вы выполняете почти одну и ту же задачу в обеих функциях и неправильно используете параметр, поэтому, например, вы можете определить индекс paymentIn по параметру typein:

function getValueToBank(provider, typein, typeout, source){
  const paymentInIndex = typein === 'credit' ? 0 : 1;
  return provider
    .filter(item => (item.country_from[0].paymentIn[paymentInIndex].type == typein 
        && item.country_from[0].currency.includes(source) 
        && item.country_from[0].paymentOut[0].type == typeout))
    .map(item => ({
        paymentIn: typein,
        paymentOut: typeout,
        paymentInFee: item.country_from[0].paymentIn[paymentInIndex].fee.number + "%",
        payInSpeed: item.country_from[0].paymentIn[paymentInIndex].speed.number + "days",
        ...item
      }))
}

И тогда вы можете выполнить свою функцию:

function getValueCreditToBank(provider, typeout, source){
    return getValueToBank(provider, 'credit', typeout, source)
    .map(y=>({  
        ...y,
        targetAmountwithPay: y.targetAmount + y.country_from[0].paymentIn[0].fee.number*y.targetAmount/100
  }))
}

function getValueDebitToBank(provider, typeout, source){
    return getValueToBank(provider, 'debit', typeout, source)
}

Таким образом, вы удаляете параметр typein из исходных функций, как это определяется именем функции.

Это всего лишь пример, вы можете переписать его разными способами, гораздо удобнее будет дать имя функциям стрелки, которые вы передаете для фильтрации и отображения массива.

0 голосов
/ 02 апреля 2019

Вот три функции:

  • getValue(obj, pin, pout, currency) - это та, которая выполняет логику.
  • getValueCreditToBank(obj, currency) является сокращением для getValue(obj, 'credit', 'bank', currency).
  • getValueDeditToBank(obj, currency) является сокращением для getValue(obj, 'debit', 'bank', currency).

Функция в настоящее время работает, только если массив country_from имеет один объект.

Логика проста:

  • Найдите в массиве объектов тот, который имеет соответствующий объект paymentIn и paymentOut и соответствующий currency.
  • Если соответствующий объект найден:
    • Рассчитать targetAmountWithPay.
    • Вернуть новый объект.

/**
 * Shorthand for getValue() with {pin = "credit"} and {pout = "bank"}.
 * @param {Object[]} obj
 * @param {string} currency
 * @returns {Object}
 */
function getValueCreditToBank(obj, currency) {
  return getValue(obj, 'credit', 'bank', currency);
}

/**
 * Shorthand for getValue() with {pin = "debit"} and {pout = "bank"}.
 * @param {Object[]} obj
 * @param {string} currency
 * @returns {Object}
 */
function getValueDebitToBank(obj, currency) {
  return getValue(obj, 'debit', 'bank', currency);
}

/**
 * @param {Object[]} obj
 * @param {string} pin
 * @param {string} pout
 * @param {string} currency
 * @returns {Object}
 */
function getValue(obj, pin, pout, currency) {
  // paymentIn and paymentOut corresponding objects found from function parameters, initialized to undefined.
  let opint, opout;
  
  // The corresponding item found from function parameters.
  const found = obj.find((item) => {
    // Gets paymentIn object from pin parameter.
    opin = item.country_from[0].paymentIn.find((pinItem) => (pinItem.type.indexOf(pin) > -1));
    
    // Gets paymentOut object from pout parameter.
    opout = item.country_from[0].paymentout.find((poutItem) => (poutItem.type.indexOf(pout) > -1));
    
    // If no paymentIn object, or no paymentOut object, or no currency found,
    // we cannot find anything.
    if (item.country_from[0].currency.indexOf(currency) === -1 || !opin || !opout) {
      return false;
    }
    
    return true;
  });
  
  // If a corresponding object is found, creates the returned object.
  if (found) {
    let targetAmountWithPay = (found.targetAmount - found.fee) * found.rate;
    targetAmountWithPay += opin.fee.number * targetAmountWithPay / 100;
  
    return {
      id: found.id,
      fee: parseFloat(found.fee),
      rate: parseFloat(found.rate),
      currency: currency,
      paymentIn: pin,
      paymentOut: pout,
      paymentInFee: `${opin.fee.number}${opin.fee.type}`,
      targetAmount: parseFloat(found.targetAmount),
      targetAmountWithPay: targetAmountWithPay
    };
  }
  
  // If not, returns null.
  return null;
}

// Tests you gave us.
console.log(getValueCreditToBank(obj, 'SGD'));
console.log(getValueDebitToBank(obj, 'THB'));

// Test if nothing is found. Should return null.
console.log(getValueCreditToBank(obj, 'EUR'));
console.log(getValueDebitToBank(obj, 'EUR'));
console.log(getValue(obj, 'credit', 'not-a-bank', 'SGD'));
console.log(getValue(obj, 'not-a-credit-nor-a-debit', 'bank', 'SGD'));
<script>
// I put your object in HTML in order to have two different frames in the snippet.
const obj = [{
    "id": "identity1",
    "fee": '2',
    "rate": '0.5',
    "targetAmount": '1000',
     "country_from": [{
        "currency": [
            "SGD",
            "USD"
        ],
        "paymentIn": [{
            "type": "credit",
            "speed": {
                "unit": "days",
                "number": "1"
            },
            "fee": {
                "type": "%",
                "number": "1.5"
            }
        },{
            "type": "debit",
            "speed": {
                "unit": "days",
                "number": "1"
            },
            "fee": {
                "type": "%",
                "number": "1"
            }
        }],
       "paymentout":[{
          "type":"bank transfer"
       }]
    }]
},
{
    "id": "identity2",
    "fee": '1',
    "rate": '0.5',
    "targetAmount": '1000',
     "country_from": [{
        "currency": [
            "THB",
            "USD"
        ],
        "paymentIn": [{
            "type": "debit",
            "speed": {
                "unit": "days",
                "number": "1"
            },
            "fee": {
                "type": "%",
                "number": "1"
            }
        }
        ],
       "paymentout":[{
          "type":"bank transfer"
       }]
    }]
}];
</script>

Если вы хотите получить ответ с обновлением функций, которые вы пытались выполнить самостоятельно, проверьте @ ответ Марио Сантини .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...