有条件地将字符串和数字的数组合并为对象数组

时间:2018-03-22 09:56:08

标签: javascript arrays react-native lodash

我有两个数组,一个是String类型,第二个是数字。如何将这些条件有条理地组合为关键值对象。

例如:

var fruits = [
  "Apple",
  "Banana" ,
  "Apricot",
  "Bilberry"
]

var count = [3,5,0,2]

我想将fruitscount数组合并为关键值对象,将合并为 0

预期:

var merge = [{"Apple":3},{"Banana" :5},{"Bilberry":2}]

我尝试的是:

var merge = _.zipObject(["Apple","Banana" ,"Apricot","Bilberry"], [3,5,0,2])

结果是:

{"Apple":3,"Banana":5 ,"Apricot":0,"Bilberry":2}

5 个答案:

答案 0 :(得分:2)

使用filterObject.valuesmap

尝试此vanilla js解决方案
var output = count.map((s, i) => ({
  [fruits[i]]: s
})).filter(s => Object.values(s)[0]);

<强>演示

&#13;
&#13;
var fruits = [
  "Apple",
  "Banana",
  "Apricot",
  "Bilberry"
];

var count = [3, 5, 0, 2];

var output = count.map((s, i) => ({
  [fruits[i]]: s
})).filter(s => Object.values(s)[0]);

console.log(output);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用_.zipObject()创建对象,然后使用_.pickBy()过滤0值的键。

注意: _.pickBy()接受回调。默认值为identity,它将过滤所有有价值的值(false,0,null,undefined等...)。如果您只想过滤零,请提供另一个回调,例如(v) => v !== 0

var fruits = ["Apple", "Banana", "Apricot", "Bilberry"];
var count = [3,5,0,2];

var result = _.pickBy(_.zipObject(fruits, count));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

使用vanilla JS,您可以使用Array.reduce()

var fruits = ["Apple", "Banana", "Apricot", "Bilberry"];
var count = [3,5,0,2];

var result = fruits.reduce(function(r, f, i) {
  if(count[i]) r[f] = count[i];
  
  return r;
}, {});

console.log(result);

答案 2 :(得分:0)

您可以使用[3, 3, 2] # 2 is the one you want to remove 创建新的对象数组&amp; map删除未定义的

filter的来源是,当计数为0时,回调函数没有返回任何值

undefined

答案 3 :(得分:0)

我认为您正在寻找的两个实用功能是:

  • zip,从[ a, b ] + [ 1, 2 ] -> [ [ a, 1 ], [ b, 2 ] ]
  • 开始
  • fromPair[ a, 1 ] -> { a: 1 }
  • 开始

通过这两个步骤拆分转换,您可以过滤键值对列表,从而确保您不会通过索引松散链接跟踪:

const valueFilter = ([k, v]) => v !== 0;

这些功能的可能实现是:

const zip = (xs, ...others) =>
  xs.map(
    (x, i) => [x].concat(others.map(ys => ys[i]))
  );

const fromPair = ([k, v]) => ({ [k]: v });

使用这些实用程序,您可以执行以下操作:

&#13;
&#13;
// Utils
const zip = (xs, ...others) =>
  xs.map(
    (x, i) => [x].concat(others.map(ys => ys[i]))
  );
  
const fromPair = ([k, v]) => ({ [k]: v });

// Data
const fruits = [ "Apple", "Banana", "Apricot", "Bilberry" ];
const counts = [3,5,0,2];

// App
const valueNotZero = ([k, v]) => v !== 0;

console.log(
  zip(fruits, counts)
    .filter(valueNotZero)
    .map(fromPair)
)
&#13;
&#13;
&#13;

答案 4 :(得分:0)

简单if(col < N-1)

forEach