本文介绍了比较字符串数组和具有字符串属性的数组对象的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,在这些对象中是一个name属性.

I have an array of object, within those objects is a name property.

const objArr = [ { name: "Avram" }, { name: "Andy" } ];

我正在从包含名称的外部来源中收集字符串数组.

I’m collecting an array of strings from an outside source containing names.

const strArr = [ "Avram", "Andy", "Brandon" ];

如果strArr包含在objArr中的对象上作为属性name不存在的字符串,我需要创建一个新对象并将其推送到objArr.

If strArr contains a string that does not exist as a property name on an object in objArr, I need to create a new object and push it to objArr.

例如:objArr.push( { name: "Brandon" } );

很显然,我可以使用嵌套循环,但如果可能的话,我想避免这种情况.以编程方式执行此操作的最佳方法是什么?

Obviously, I can use nested loops, but I’d like to avoid that if possible. What is the best way to do this programmatically?

推荐答案

const objArr = [ { name: "Avram" }, { name: "Andy" } ];
const strArr = [ "Avram",  "Andy",  "Brandon" ];

const objNamesArr = objArr.map((obj) => obj.name)

strArr.forEach((ele) => objNamesArr.indexOf(ele) == -1 && objArr.push({name:ele}))
console.log('objArr', objArr);
console.log('strArr', strArr);

这篇关于比较字符串数组和具有字符串属性的数组对象的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:43