更新两个JavaScript对象中的匹配键值

时间:2018-02-02 14:45:18

标签: javascript angularjs

我的要求是比较两个对象并将更新的值复制到第二个对象的第一个对象中。 例如:

$scope.obj1={"id" : 1, "name" : "java"}
$scope.obj2={"id" : 1, "name" : "java4you", "gender" : "male"}

compare(destination, bj1, obj2);

目标变量输出:

{"id" : 1, "name" : "java4you"}

上述两个对象包含相同的键,但值不同。我必须比较obj1和obj2并用匹配的obj2值更新

5 个答案:

答案 0 :(得分:0)

试试这个,

class MainScreenFragment : Fragment() {


var getSongList : ArrayList<Songs>? = null
var nowPlayingBottomBar: RelativeLayout?=null
var playPauseButton: ImageView?=null
var songTitle: TextView?=null
var visibleLayout: RelativeLayout?=null
var noSongs: RelativeLayout?=null
var recyclerView: RecyclerView?= null

var myActivity:Activity?=null

var _mainScreenAdapter : MainScreenAdapter?=null

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

    val view = inflater?.inflate(R.layout.content_main, container, false)
    setHasOptionsMenu(true)
    activity.title = "All songs"
    visibleLayout = view?.findViewById<RelativeLayout>(R.id.visibleLayout)
    noSongs = view?.findViewById<RelativeLayout>(R.id.noSongs)
    nowPlayingBottomBar = view?.findViewById<RelativeLayout>(R.id.hiddenBarMainScreen)
    songTitle = view?.findViewById<TextView>(R.id.songTitleMainScreen)
    playPauseButton = view?.findViewById<ImageButton>(R.id.playpauseButton)
    (nowPlayingBottomBar as RelativeLayout).isClickable = false
    recyclerView = view?.findViewById<RecyclerView>(R.id.contentMain)

    visibleLayout?.visibility = View.INVISIBLE
    noSongs?.visibility = View.VISIBLE



   //getting error on this line->
   _mainScreenAdapter = MainScreenAdapter(getSongList as ArrayList<Songs>, activity)
    val mLayoutManager = LinearLayoutManager(activity)
    (recyclerView as RecyclerView).layoutManager = mLayoutManager
    (recyclerView as RecyclerView).itemAnimator = DefaultItemAnimator()
    (recyclerView as RecyclerView).adapter = _mainScreenAdapter
    return view




}

fun getSongsFromPhone(): ArrayList<Songs>{
    var arrayList = ArrayList<Songs>()
    var contentResolver = myActivity?.contentResolver
    var songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    var songCursor = contentResolver?.query(songUri, null, null, null, null)
    if(songCursor!=null && songCursor.moveToFirst()){
        val songId = songCursor.getColumnIndex(MediaStore.Audio.Media._ID)
        val SongTitle = songCursor.getColumnIndex((MediaStore.Audio.Media.TITLE))
        val songArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)
        val songData = songCursor.getColumnIndex(MediaStore.Audio.Media.DATA)
        val dateIndex = songCursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)

        while(songCursor.moveToNext()){
            var currentId = songCursor.getLong(songId)
            var currentTitle = songCursor.getString(SongTitle)
            var currentArtist = songCursor.getString(songArtist)
            var currentData = songCursor.getString(songData)
            var currentDate = songCursor.getString(dateIndex)
        }
    }
    return arrayList
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    getSongList = getSongsFromPhone()

}


override fun onAttach(context: Context?) {
    super.onAttach(context)
    myActivity = context as Activity
}

override fun onAttach(activity: Activity?) {
    super.onAttach(activity)
    myActivity = activity
}

用法应该是,

function compare(obj1, obj2)
{
    let obj = {};
    for(let k in obj1)
    {
         obj[k] = obj2[k];
     }
    return obj;
}

答案 1 :(得分:0)

如果没有实际引用可在angularJs中使用的方法,您可以试试这个:

&#13;
&#13;
function compare(o1, o2) {
  var biggest = o1;
  
  if (Object.keys(o2).length > Object.keys(o1).length) {
    biggest = o2;
  }

	for (let key in biggest) {
  	if (!biggest.hasOwnProperty(key)) continue;
    
    if (o1[key] != o2[key]) {
    	console.info("Difference in '"+ key +"': "+ o1[key] +" <> "+ o2[key]);
    }
	}
}

var $scope = {};

$scope.obj1 = {"id" : 1, "name" : "java"};
$scope.obj2 = {"id" : 1, "name" : "java4you", "gender" : "male"};

compare($scope.obj1, $scope.obj2);
&#13;
&#13;
&#13;

但要小心使用它,因为它有许多可能的失败案例。

答案 2 :(得分:0)

使用Angularjs,您可以使用.equal进行比较并获得结果,我不会看到什么不起作用或提供您的代码只会得到答案。

$scope.result = angular.equals($scope.obj1, $scope.obj2);
if($scope.result === true){    
$scope.obj1 = $scope.obj2;
}

答案 3 :(得分:0)

您可以在新变量obj1中使用Object.assign()创建destination的副本,并使用obj2和{{遍历Object.keys()的每个键1}}并检查array#forEach中是否存在密钥,如果密钥存在,则从destination

的值更新destination中的值

&#13;
&#13;
obj2
&#13;
&#13;
&#13;

答案 4 :(得分:0)

我必须更新@Bharadwaj答案才能为我工作。
for(... in ...)语句必须使用if语句进行过滤

    var obj1={"id" : 1, "name" : "java"},
        obj2={"id" : 1, "name" : "java4you", "gender" : "male"};

    function compare(obj1, obj2) {
      let obj = {};
      for(let k in obj1) {
         if(obj1[k] !== obj2[k]) {
           obj = Object.assign({}, obj1, obj1[k] = obj2[k]);
         }
         
      }
      return obj;
    }